我有一个应用程序发送命令bash如下:
/bin/bash -c "<command goes here>"
这很好用,但我遇到了一个稍微复杂一点的问题。此命令从SSH服务器获取tar,显示带有pv
的进度条,然后将其保存到本地用户的目录。
su -c "ssh -p 1234 [email protected] 'cd /home/ && tar -cf - remoteuser/' | pv > /home/staging/localuser/staging.tar" localuser
在命令行上手动运行此命令效果很好,但我不能在我的生活中找出如何将此作为参数传递给/bin/bash/
。
我试过了:
/bin/bash -c "su -c "ssh -p 1234 [email protected] 'cd /home/ && tar -cf - remoteuser/' | pv > /home/staging/localuser/staging.tar" localuser"
各种组合使用不同的语法,但我只是猜测,因为我不明白为什么它不起作用。
我把它分解为一个更简单的例子,并意识到如果内部命令使用单引号就像这个获得主路径的简单示例一样:
bash -c "su -c 'cd ~ && pwd' localuser"
但是在较大的命令上尝试它会导致它失败:
/bin/bash -c "su -c 'ssh -p 1234 [email protected] 'cd /home/ && tar -cf - remoteuser/' | pv > /home/staging/localuser/staging.tar' localuser"
它说no passwd entry for user /home
因此命令被打破我想买嵌套的单引号但我不知道如何解决这个问题。
我试过在单引号之外加双引号:
/bin/bash -c "su -c 'ssh -p 1234 [email protected] "'cd /home/ && tar -cf - remoteuser/'" | pv > /home/staging/localuser/staging.tar' localuser"
但后来它说无法找到目录。看起来我只需稍微调整一下命令,但我无法弄清楚,有人可以帮忙吗?
这是以正确方式引用的问题。有不止一种方法可以做到这一点。在这种情况下,我发现双引号更易于使用:
echo "su -c \"ssh -p 1234 [email protected] 'cd /home/ && tar -cf - remoteuser/' | pv > /home/staging/localuser/staging.tar\" localuser"
打印:
su -c "ssh -p 1234 [email protected] 'cd /home/ && tar -cf - remoteuser/' | pv > /home/staging/localuser/staging.tar" localuser
我认为这就是你要找的东西。也就是说,用\"
转义外部双引号内的任何双引号。所以尝试:
/bin/bash -c "su -c \"ssh -p 1234 [email protected] 'cd /home/ && tar -cf - remoteuser/' | pv > /home/staging/localuser/staging.tar\" localuser"
这就是这里 - 文件派上用场:
bash <<'END'
su -c "ssh -p 1234 [email protected] 'cd /home/ && tar -cf - remoteuser/' | pv > /home/staging/localuser/staging.tar" localuser
END
请注意,-c
选项已被删除:bash将从stdin读取命令。