bash 通过 ssh 连接 sed + `s' 的未知选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17027882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sed over ssh connection + unknown option to `s'
提问by gjw80
I have a sed command in a bash script like this:
我在 bash 脚本中有一个 sed 命令,如下所示:
sed -i 's/db.url=.*/db.url='$URL'/' config.properties
and URL var is assigned as:
并且 URL 变量被分配为:
$URL=jdbc\:oracle\:thin\:@\/\/hostname\:12345\/XYZ
When I run this bash script on the host it exists on it work as intended, replacing the url with the one specified in URL. However, when I add a command in the bash script to do this on my other host like this:
当我在主机上运行这个 bash 脚本时,它按预期工作,用 URL 中指定的 URL 替换它。但是,当我在 bash 脚本中添加命令以在我的其他主机上执行此操作时,如下所示:
ssh user@host02 <<EOF
sed -i 's/db.url=.*/db.url='$URL'/' config.properties
exit
EOF
I get this error:
我收到此错误:
sed: -e expression #1, char 47: unknown option to `s'
Anyone know what may be going on here?
有谁知道这里会发生什么?
采纳答案by gjw80
The solution was to use double single quotes (') around $URL like this: ''$URL''
解决方案是在 $URL 周围使用双单引号 ('),如下所示:''$URL''
回答by chepner
You've properly quote the sedexpression if it were running on the local host, but the string is then passed to the shell on the remotehost, where the *is now unquoted and expanded as a glob. The simplest thing to do is to pipe the command to the remote shell via standard input, so you don't have to worry about quoting:
如果sed表达式在本地主机上运行,则您已经正确地引用了该表达式,但是该字符串随后被传递到远程主机上的 shell ,在那里*现在不加引号并扩展为 glob。最简单的做法是通过标准输入将命令通过管道传送到远程 shell,因此您不必担心引用:
echo "sed -i 's/db.url=.*/db.url=$URL/' config.properties" | ssh user@host02 bash
With multiple commands, you may consider using a here document:
对于多个命令,您可以考虑使用此处的文档:
ssh user@host02 bash <<EOF
command1
sed -i 's/db.url=.*/db.url=$URL/' config.properities
command2
EOF

