来自中央Linux盒子(RHEL 6.3)我正在尝试将一组zip文件推送到一系列其他Linux主机,然后在每个目标主机上解压缩这些文件。我的中央主机是 hpdb1。
#Push zip files to other hosts
for i in {2..8}; do
scp -r /software/stage/*.zip root@hpdb$i:/software/stage
done
#Unzip files to /software/stage
for i in {2..8}; do
ssh hpdb$i "for f in /software/stage/*.zip; do unzip /software/stage/"$f" done";
done
第一个用于推送文件的 for 循环工作正常。但是,在运行嵌套的 for 循环时,我收到以下错误:
[root@hpdb1 ~]# for i in {2..8}; do ssh hpdb$i "for f in /software/stage/*.zip; do unzip /software/stage/"$f"; done"; done
unzip: cannot find or open /software/stage/, /software/stage/.zip or /software/stage/.ZIP.
unzip: cannot find or open /software/stage/, /software/stage/.zip or /software/stage/.ZIP.
看起来$f
变量没有得到解释。有什么想法吗?
更新答案
此代码有效。
for i in {2..7}; do
ssh hpdb$i 'for f in /software/stage/*.zip; do unzip "$f" -d /software/stage; done';
done
问题可能是嵌套的双引号。 您可能希望外部引号为单引号,以便在发送到远程服务器之前不会扩展嵌入式$
。
我的第一个是使用另一个引号字符,例如:
for i in {2..8}; do ssh hpdb$i 'for f in /software/stage/*.zip; do unzip /software/stage/“$f”; done'; done
尽管您可以按照另一个答案的建议使用不同的引号,但这会改变变量扩展行为,并且在某些情况下可能是不可取的。
您可以简单地转义括起来的引号,方法是在它们前面加上反斜杠:
for i in {2..8}; do
ssh hpdb$i "for f in /software/stage/*.zip; do unzip /software/stage/"$f"; done";
done