【发布时间】:2013-11-03 11:20:30
【问题描述】:
我有一个简单的 bash 脚本可以在给定的一组服务器上运行远程命令。
#!/bin/bash
echo "Command to be run:"
echo "$*"
read nothing
servers="server1 server2 server3"
for server in `echo $servers`
do
echo $server
ssh $server "$*"
echo ""
done
问题是命令可以包含任意数量的参数,因此使用 $* 并且还可以包含许多不同的字符,包括引号和正则表达式。这里的基本需求是让 shell 接受参数,不管它们是什么,从字面上看,这样它们就可以原封不动地传递给远程服务器,而无需删除引号或解释括号等。
我见过许多变体,但大多数都处理特定的字符问题或使所需的脚本或参数过于复杂,我希望至少使参数不包含转义字符等。
一个使用“@”的例子:
./cmd tw_query --no-headings "search Host where name matches '(?i)peter' show summary, nodecount(traverse :::Detail where name matches 'bob')"
给予:
Command to be run:
tw_query --no-headings search Host where name matches '(?i)peter' show summary, nodecount(traverse :::Detail where name matches 'bob')
【问题讨论】:
-
使用
"$@"而不是"$*"这应该可以解决您的问题。 -
您可以将
for server inecho $servers` ` 替换为for server in $servers -
将这样的字符串传递给
ssh很困难,因为在调用脚本和设置$*之前会解析一次字符串,然后在远程端接收到字符串时再解析一次。编写脚本,将其复制到远程主机,然后通过ssh执行远程脚本通常更容易。