用bash转义引号(Embedded awk) [英] Escaping quotes in bash (Embedded awk)
问题描述
我有一个复杂的命令,我要通过ssh传递给远程服务器.我正在尝试解压缩文件,然后在第二个ssh命令中更改其命名结构和扩展名.我的命令是:
I have a complex command I am passing via ssh to a remote server. I am trying to unzip a file and then change its naming structure and extension in a second ssh command. The command I have is:
ssh root@server1 "gzip -d /tmp/file.out-20171119.gz; echo file* | awk -F'[.-]' '{print $1$3".log"}'"
很明显,打印语句的.log部分周围的使我失败.我的想法是,我将从文件名中删除.out部分,最后得到file20171119.log作为结束结果.对语法或如何正确进行转义感到困惑,因此bash会正确解释.log.
Obviously the " around the .log portion of the print statement are failing me. The idea is that I would strip the .out portion from the filename and end up with file20171119.log as an ending result. I am just a bit confused on the syntax or on how to escape that properly so bash interprets the .log appropriately.
推荐答案
解决此问题的最简单方法是避免它.不必费心尝试转义脚本以进入命令行:而是在stdin上传递它.
The easiest way to deal with this problem is to avoid it. Don't bother trying to escape your script to go on a command line: Pass it on stdin instead.
ssh root@server1 bash -s <<'EOF'
gzip -d /tmp/file.out-20171119.gz
# note that (particularly w/o a cd /tmp) this doesn't do anything at all related to the
# line above; thus, probably buggy as given in the original question.
echo file* | awk -F'[.-]' '{print $1$3".log"}'
EOF
一个带引号的heredoc-用<<'EOF'
或<<\EOF
而不是<<EOF
的字体-按原样传递,没有任何shell扩展;因此,$1
或$3
不会被调用shell取代,就像被带引号的heredoc取代一样.
A quoted heredoc -- one with <<'EOF'
or <<\EOF
instead of <<EOF
-- is passed literally, without any shell expansions; thus, $1
or $3
will not be replaced by the calling shell as they would with an unquoted heredoc.
如果您不想走回避路线,则可以让Shell自己为自己报价.例如:
If you don't want to go the avoidance route, you can have the shell do the quoting for you itself. For example:
external_function() {
gzip -d /tmp/file.out-20171119.gz
echo file* | awk -F'[.-]' '{print $1$3".log"}'
}
ssh root@server1 "$(declare -f external_function); external_function"
declare -f
打印功能的定义.将函数按字面意义放入SSH命令中可确保它可以远程运行.
declare -f
prints a definition of a function. Putting that function literally into your SSH command ensures that it's run remotely.
这篇关于用bash转义引号(Embedded awk)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!