shell脚本中的超时

shell脚本中的超时,shell,Shell,我想在shell脚本中设置超时,以便在该脚本中完成进程,例如,如果我想scp一个文件,如果该文件没有通过错误在超时内传输,如果成功回显成功消息,如何设置超时?例如: command & # start a new process in background pid=$(pidof command | cut -f1 -d' ') # save pid of started process sleep(timeout_value) # set timeout value

我想在shell脚本中设置超时,以便在该脚本中完成进程,例如,如果我想scp一个文件,如果该文件没有通过错误在超时内传输,如果成功回显成功消息,如何设置超时?

例如:

command &    # start a new process in background
pid=$(pidof command | cut -f1 -d' ')    # save pid of started process
sleep(timeout_value)    # set timeout value to match your desired time to process
pids=$(pidof command)    # get all pids of running processes of this command
if [[ $(grep "$pid" "$pids") ]]; then    # if started process still running
    echo "error"
else
    echo "success"
fi
更改单词command以匹配实际命令。我不确定这是否适用于管道,我将在一分钟内进行测试,然后返回给您

对于管道命令,可以执行以下操作(前提是使用bash执行):

问题

请注意,还有更好的答案,因为此脚本将始终等待整个超时。这可能不是你想要的

可能的解决方案

一个可能的解决方案是多次睡眠,类似这样:

for i in $(seq 1..100); do
    sleep(timeout/100)  # sample the timeout interval
    pids=$(pidof bash)
    if [[ $(grep -v "$pid" "$pids") ]]; then   # if process no longer running
        echo "succes" && exit 0     # process completed, success!
    elif [[ $i -eq 100 ]]; then
        echo "error"    # at the end of our timeout
    fi
done

注意:如果超时很长,请更改值100,尝试对其进行优化,使每次迭代的超时不会太长。

使用。比你必须编写、调试和维护的自制解决方案要好得多。

该死,我知道有一个更优雅的解决方案:D我想我在这里学到了宝贵的一课,尽管在shell脚本编写方面做一点练习从来都不是坏事!作为练习,绝对不是。作为开发时间,我不认为是。它通常会导致需要时间和精力来维护的脆弱代码。完全同意,因此我投票支持你的答案。我不敢相信我不知道图伊斯的内置命令。
for i in $(seq 1..100); do
    sleep(timeout/100)  # sample the timeout interval
    pids=$(pidof bash)
    if [[ $(grep -v "$pid" "$pids") ]]; then   # if process no longer running
        echo "succes" && exit 0     # process completed, success!
    elif [[ $i -eq 100 ]]; then
        echo "error"    # at the end of our timeout
    fi
done