最多重试 10 次 scp 命令,直到成功

最多重试 10 次 scp 命令,直到成功

我希望重试scp10 次,如果失败则打印错误消息。

下面是我的代码:

#!/bin/bash
FILE=$1;
echo $FILE;

HOMEDIR="/home/ibro";
tries=0;
while (system "scp -P 3337 $FILE ibrahimince\@localhost:$HOMEDIR/Printed/")
do
    last if $tries++ > 10;
    sleep 3;
done

if [ $? -eq 0 ]; then
echo "SCP was successful"
else
echo " SCP failed"
fi

不幸的是,我收到以下错误:

npm-debug.log
./test.sh: line 8: system: command not found

下面是根据@roaima建议的详细输出

$ shellcheck myscript
 
Line 3:
echo $FILE;
     ^-- SC2086: Double quote to prevent globbing and word splitting.

Did you mean: (apply this, apply all SC2086)
echo "$FILE";
 
Line 9:
    last if $tries++ > 10;
                     ^-- SC2210: This is a file redirection. Was it supposed to be a comparison or fd operation?

$

您能帮忙纠正一下代码吗?

答案1

更改您想要的任何参数或为文件创建一个新变量。

#!/bin/bash

# Trap interrupts and exit instead of continuing the loop
trap "echo Exited!; exit;" SIGINT SIGTERM

MAX_RETRIES=10
i=0

# Set the initial return value to failure
false

while [ $? -ne 0 -a $i -lt $MAX_RETRIES ]
do
 i=$(($i+1))
 scp -P 3337 my_local_file.txt user@host:/remote_dir/
done

if [ $i -eq $MAX_RETRIES ]
then
  echo "Hit maximum number of retries, ending."
fi

答案2

retry工具将执行此操作。按照要求,我们尝试了10次才放弃。

默认情况下,我们会永远重试。

~$ retry --times 10 -- scp -P 3337 $FILE ibrahimince@localhost:$HOMEDIR/Printed/
ssh: connect to host localhost port 3337: Connection refused
scp: Connection closed
retry: scp returned 255, backing off for 10 seconds and trying again...
ssh: connect to host localhost port 3337: Connection refused
scp: Connection closed
retry: scp returned 255, backing off for 10 seconds and trying again...
ssh: connect to host localhost port 3337: Connection refused
scp: Connection closed
retry: scp returned 255, backing off for 10 seconds and trying again...
ssh: connect to host localhost port 3337: Connection refused
scp: Connection closed
retry: scp returned 255, backing off for 10 seconds and trying again...
ssh: connect to host localhost port 3337: Connection refused
scp: Connection closed
retry: scp returned 255, backing off for 10 seconds and trying again...
ssh: connect to host localhost port 3337: Connection refused
scp: Connection closed
retry: scp returned 255, backing off for 10 seconds and trying again...
ssh: connect to host localhost port 3337: Connection refused
scp: Connection closed
retry: scp returned 255, backing off for 10 seconds and trying again...
ssh: connect to host localhost port 3337: Connection refused
scp: Connection closed
retry: scp returned 255, backing off for 10 seconds and trying again...
ssh: connect to host localhost port 3337: Connection refused
scp: Connection closed
retry: scp returned 255, backing off for 10 seconds and trying again...
ssh: connect to host localhost port 3337: Connection refused
scp: Connection closed
retry: scp returned 255, backing off for 10 seconds and trying again...
~$ 

https://github.com/minfrin/retry

在最新的 Debian、Ubuntu 和 Nix 中开箱即用。

(免责声明,我是该工具的原作者)

相关内容