嵌套for循环的问题

时间:2014-02-14 16:43:20

标签: linux bash for-loop ssh

从中央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

3 个答案:

答案 0 :(得分:2)

问题可能是嵌套的双引号。您可能希望外引号为单引号,以便嵌入的$在发送到远程服务器之前不会展开。

答案 1 :(得分:1)

我的第一个是使用其他引用字符,所以:

for i in {2..8}; do ssh hpdb$i 'for f in /software/stage/*.zip; do unzip /software/stage/“$f”; done'; done

答案 2 :(得分:0)

虽然您可以使用另一个答案建议的不同引号,但这会改变变量扩展行为,在某些情况下可能不合适。

您可以简单地转义所附的引号,方法是使用反斜杠预先挂起它们:

for i in {2..8}; do 
  ssh hpdb$i "for f in /software/stage/*.zip; do unzip /software/stage/\"$f\"; done";
done