如何在 shell 中设置定时器

How to set the timer in shell

我们可以在 shell 脚本中设置定时器吗? 意味着如果我将计时器设置为 20 秒,我的 shell 脚本应该像这样执行:

20..19..18..17..

完成后我应该得到结果。可能吗 ?请帮助我。

不完全清楚你想要什么:如果 xyz.sh 在 3 秒内完成,你想再等 17 秒吗?或者你想在 20 秒后中断 xyz.sh 并让它产生输出?如果是后者:

$ cat a.sh
#!/bin/bash 

./xyz.sh &

i=${1-20}
echo
while test $i -gt 0; do printf "\r$((i--))..."; sleep 1; done
kill $!


$ cat xyz.sh 
#!/bin/sh

foo() { echo "this program doesn't do much"; }
trap foo TERM
sleep 30 &
wait

for 循环看起来像:

#!/bin/bash
for (( i=20; i>0; i-- ))
do
clear
echo -n "$i"
sleep 1
done