SSH嵌套的grep [英] Nested grep with SSH

查看:101
本文介绍了SSH嵌套的grep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下成功运行的Shell命令:

I have a following Shell command which runs successfully:

sed -e "1,/^$(date -d -24hour +'%Y-%m-%d %H')/d" logfile | grep -A20 -B10 'Exception' | mail -s "Sample report" xyz@yourdomain

但是,我必须通过SSH到特定计算机上才能运行它.为避免这种情况,我通过以下方式对其进行了修改,导致失败:

However, I have to SSH to a particular machine to run this. To avoid this, I modified it in following way which leads to the failure:

ssh myserver 'sed -e "1,/^$(date -d -24hour +'%Y-%m-%d %H')/d" logfile | grep -A20 -B10 'Exception' | mail -s "Sample report" xyz@yourdomain '

此命令有什么问题?我该如何解决?

What is wrong with this command? How can I fix this?

推荐答案

将您的代码嵌入带引号的heredoc中,以避免对其进行修改(从本质上讲,这是一个容易出错的过程):

Embed your code in a quoted heredoc to avoid needing to modify it (which is an error-prone process by nature):

ssh myserver 'bash -s' <<'EOF'
  sed -e "1,/^$(date -d -24hour +'%Y-%m-%d %H')/d" logfile \
    | grep -A20 -B10 'Exception' \
    | mail -s "Sample report" xyz@yourdomain
EOF


在这里的特定情况下,您的原始修改失败的明显原因是内部单引号终止了整个代码周围的引号.


In the specific case here, the obvious reason that your original modifications failed was internal single quotes terminating the ones surrounding the code as a whole.

特别是:

+'%Y-%m-%d %H'

...该表达式中的第一个'会终止命令前的一个开头,因此该空间不会受到语法保护.

...the first ' in that expression terminates the one opening before the command, so the space isn't syntactically protected.

您可以执行以下操作,因为您的shell是bash:

You could instead do the following, since your shell is bash:

ssh myserver $'sed -e "1,/^$(date -d -24hour +\'%Y-%m-%d %H\')/d" logfile | grep -A20 -B10 Exception | mail -s "Sample report" xyz@yourdomain'

$''是扩展名,反斜杠可以在其中转义单引号(也可用于其他文字- \ n 用于换行符 \t (用于制表符等),该功能不适用于典型的POSIX sh语法.

$'' is an extension within which backslashes can escape single quotes (and also be used for other literals -- \n for a newline, \t for a tab, etc), functionality not available with typical POSIX sh syntax.

相比之下,在POSIX sh中,可以切换引用类型以嵌入文字单引号:'foo''"'bar'来定义一个字符串,同时包含两个 foo bar 用单引号引起来,并在它们之间用单个文字单引号分隔-完全有效的语法,但对于不熟悉该惯用语的读者来说不一定容易).

By contrast, in POSIX sh, one can switch quoting types to embed a literal single-quote: 'foo'"'"'bar' to defines a string with both foo and bar single-quoted, and separated by a single literal single-quote between them -- perfectly valid syntax, but not necessarily easy for readers unfamiliar with the idiom to process).

这篇关于SSH嵌套的grep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆