![为什么ssh远程调用命令替换失败?](https://linux22.com/image/29734/%E4%B8%BA%E4%BB%80%E4%B9%88ssh%E8%BF%9C%E7%A8%8B%E8%B0%83%E7%94%A8%E5%91%BD%E4%BB%A4%E6%9B%BF%E6%8D%A2%E5%A4%B1%E8%B4%A5%EF%BC%9F.png)
我有这个脚本:
exportFile(){
file=$1
skippedBytes=$2
exportCommandString=$3
#This works:
#dd if=$file bs=1 skip=$skippedBytes | ssh sshConnection 'cat - >> /remote/dir/myTarget.txt.output' > export.output 2>&1
#This does not work:
dd if=$file bs=1 skip=$skippedBytes | $($exportCommandString $file) > export.output 2>&1
cat export.output
}
sshExportCommand(){
userAtServer=$1
targetDir=$2
filename=$3
echo 'ssh '$userAtServer' '\''cat - >> '$targetDir'/'$filename'.output'\'
#Same result with this:
#echo "ssh $userAtServer 'cat - >> $targetDir/$filename.output'"
}
exportFile mySource.txt 9 "sshExportCommand sshConnection /remote/dir myTarget.txt"
调用它时,我获得以下输出:
85+0 records in
85+0 records out
85 bytes (85 B) copied, 0.00080048 s, 106 kB/s
Read bytes: 85
ovh_ssh: cat - >> /remote/dir/myTarget.txt.output: No such file or directory
是什么阻止了这个工作?这是命令替换吗?我还错过了什么吗?
答案1
正如您在注释代码行中所写,以下内容正在运行:
byteCount=$( exec 3>&1 ; dd if=$file bs=1 skip=$skippedBytes | tee -a >(wc -c >&3) -a $file.output | ssh sshConnection 'cat - >> /remote/dir/myTarget.txt.output' > export.output 2>&1 ; 3>&1 )
因此,适应这些知识并使用这种重构:
exportFile(){
file=$1
skippedBytes=$2
userAtServer=$3
targetDir=$4
targetFile=$5
rm export.output
byteCount=$( exec 3>&1 ; dd if=$file bs=1 skip=$skippedBytes | tee -a >(wc -c >&3) -a $file.output | ssh ${userAtServer} "cat - >>$targetDir/${targetFile}" > export.output 2>&1 ; 3>&1 )
echo "Read bytes: $byteCount"
cat export.output
}
exportFile mySource.txt 9 sshConnection /remote/dir myTarget.txt