-1

我的代码是:

nb_lignes=`wc -l $1 | cut -d " " -f1`
for i in $(seq $(($nb_lignes - 1)) )
do
machine=`head $1 -n $i | tail -1`
machine1=`head $1 -n $nb_lignes | tail -1`
ssh root@$machine -x " scp /home/file.txt root@$machine1:/home && rm -r /home/file.txt"
done

$machine1 是作为变量还是字符串?如果是字符串,我该如何更改它——通过添加引号?

4

3 回答 3

2

$machine将扩大到head $1 -n $i | tail -1结果,$machine1将扩大到head $1 -n $nb_lignes | tail -1结果。

你可以自己想办法。

顺便说一句,ssh root@……</p>

于 2012-10-22T13:55:30.100 回答
1

$machine1将被扩展以给出变量的值machine1,因为您使用的是双引号"。如果您使用了单引号',那么它就不会被扩展。

一种可能的混淆是当您在其他文本中嵌入变量时。在这种情况下,你很好,因为尾随字符是:( root@$machine1:/home),它不是 Bash 变量名称中的有效字符。有些 shell (csh) 不喜欢这样,如果您不确定,那么您可以使用 分隔变量名{ },例如:

root@${machine1}:/home
于 2012-10-22T14:06:18.177 回答
0

重写的答案

不管ssh root那里有什么滥用......(我更喜欢curl为此目的使用,但你必须自己写collectFiles.php;)

好的,这样做的目的是将主机列表的最后一行作为destination,从列表的其余部分发送文件到哪里。你可以:

Posix外壳优先:

下测试

tac $1  | (
    srcFile=/home/file.txt i=1
    read destHost
    while read collectHost ;do
        destFile=`printf "root@%s:/home/fileHost_%-12s_%03d.txt" \
            $destHost $collectHost $i`
        i=$((i+1))
        echo ssh $collectHost -x "curl -H 'Filename: $destFile' \
            --data-binary '@$srcFile http:/$destHost/collectFiles.php && \
                rm $srcFile"
        done
)

echo将被丢弃)

操作变量提供了一种构建命令的好方法,有一个完整的可用示例

#!/bin/bash

mapfile flist <$1

dstCmdFmt="curl -H 'Filename: %s' --data-binary '@%s' http://%s/%s && rm %s"
dstRcvPhp=collectfiles.php
srcFile=/home/file.txt

for ((i=0;i<${#flist[@]}-1;i++));do
    printf -v destFile "fileHost_%-12s_%03d.txt" ${flist[i]} $[1+i]
    printf -v cmd "$dstCmdFmt" \
        ${destFile// /_} $srcFile ${flist[@]:${#flist[@]}-1} $dstRcvPhp $srcFile
    echo ssh ${flist[i]} -x "$cmd"
done

尝试使用文件:

cat <<eof > testfile
machineA
OtherMachine
AnotherHost
DestinationHost
eof

./script.sh testfile
ssh machineA -x curl -H 'Filename: fileHost_machineA_____001.txt' --data-binary '@/home/file.txt' http://DestinationHost/collectfiles.php && rm /home/file.txt
ssh OtherMachine -x curl -H 'Filename: fileHost_OtherMachine_002.txt' --data-binary '@/home/file.txt' http://DestinationHost/collectfiles.php && rm /home/file.txt
ssh AnotherHost -x curl -H 'Filename: fileHost_AnotherHost__003.txt' --data-binary '@/home/file.txt' http://DestinationHost/collectfiles.php && rm /home/file.txt

旧答案

代替...

nb_lignes=`wc -l <$1`
machine1=`sed -ne ${nb_lignes}p <$1`
for i in `seq $(($nb_lignes - 1))` ;do
    machine=`sed -ne ${i}p <$1`
    ssh  root@$machine -x " scp /home/file.txt root@$machine1:/home && rm -r /home/file.txt"
  done

但...

如果从每个machine,您确实发送不同file.txt(但名称相同)到同一目标目录中的相同唯一machine文件,您每次都将覆盖先前发送的文件。

于 2012-10-24T23:49:13.050 回答