如何将变量名称替换为命令中的文件名?

时间:2022-06-02 05:58:14

I am trying to make a script that runs through all the machines available and saves some data into my home folder.

我正在尝试制作一个运行所有可用机器的脚本,并将一些数据保存到我的主文件夹中。

machines=`cat $OAR_FILE_NODES | uniq`
for machine in ${machines}
do
    echo "connecting to:" ${machine}
    oarsh ${machine} 'tar -zcvf data_${machine}.tar.gz /tmp/data'
done 

The problem is that all data gets saved to data_.tar.gz archive, overwriting it several times.

问题是所有数据都保存到data_.tar.gz存档,多次覆盖。

How can I make the shell substitute the variable machine into the command passed to oarsh?

如何让shell将变量机器替换为传递给oarsh的命令?

1 个解决方案

#1


1  

As seen on the comments, it was about the variable not expanding because of the single quote '. By changing to double quotes " the variable is expanded properly:

正如评论中所看到的那样,由于单引号而导致变量没有扩大。通过更改为双引号“变量正确扩展:

oarsh ${machine} "tar -zcvf data_${machine}.tar.gz /tmp/data"
                 ^                                          ^

Note that when using a single quote, what oarsh would receive is the literal:

请注意,当使用单引号时,oarsh会收到的是文字:

tar -zcvf data_${machine}.tar.gz /tmp/data

while using double quotes would provide the $machine value replaced:

使用双引号将提供$ machine值替换:

tar -zcvf data_THE_MACHINE.tar.gz /tmp/data

#1


1  

As seen on the comments, it was about the variable not expanding because of the single quote '. By changing to double quotes " the variable is expanded properly:

正如评论中所看到的那样,由于单引号而导致变量没有扩大。通过更改为双引号“变量正确扩展:

oarsh ${machine} "tar -zcvf data_${machine}.tar.gz /tmp/data"
                 ^                                          ^

Note that when using a single quote, what oarsh would receive is the literal:

请注意,当使用单引号时,oarsh会收到的是文字:

tar -zcvf data_${machine}.tar.gz /tmp/data

while using double quotes would provide the $machine value replaced:

使用双引号将提供$ machine值替换:

tar -zcvf data_THE_MACHINE.tar.gz /tmp/data