myscp=$(sshpass -p testserver scp -rP 8888 root@localhost:/test/server/ ~/local/)
我该如何在此行中添加条件语句?如果管道损坏,scp 将停止/中断,否则如果管道已打开以进行连接,则将继续
if "$myscp" == 0; then
echo "SUCCESS)."
else
echo "**FAILED)."
echo "$myscp"
exit
echo "Done........ 100.0%"
此示例不起作用
答案1
第一个例子保存了 sshpass 的返回代码:
#!/bin/bash
sshpass -p password \
scp -rq -P 22 user@localhost:~/src/path ~/dest/path
c=$?
if ((!$c)); then
echo "Success!"
else
echo "Failed: exit code ($c)."
fi
或者您可以直接在 if-then 语句中使用命令:
#!/bin/bash
if sshpass -p password \
scp -rq -P 22 user@localhost:~/src/path ~/dest/path; then
echo "Success!"
else
echo "Failed!"
fi
我强烈建议您不要使用密码,而是使用密钥认证。
答案2
该$?
变量设置为最后执行的命令的返回代码
sshpass -p testserver scp -rP 8888 root@localhost:/test/server/ ~/local/
if [ $? == 0 ];
then echo "SUCCESS)."
else
echo "**FAILED)."
echo "Exit code: $?"
exit
echo "Done........ 100.0%"
fi