如何在 Bash 中重复循环 n 次

Roc*_*y86 18 bash shell-script

我有以下场景:

if [file exists]; then
   exit   
elif
   recheck if file exist (max 10 times)
   if found exit else recheck again as per counter  
fi 
Run Code Online (Sandbox Code Playgroud)

xen*_*oid 22

如果计数不是变量,则可以使用大括号扩展:

for i in {1..10}   # you can also use {0..9}
do
  whatever
done
Run Code Online (Sandbox Code Playgroud)

如果计数是一个变量,您可以使用以下seq命令:

count=10
for i in $(seq $count)
do
  whatever
done
Run Code Online (Sandbox Code Playgroud)


Kus*_*nda 19

有很多方法可以执行此循环。

使用ksh93语法(也由zsh和支持bash):

for (( i=0; i<10; ++i)); do
    [ -e filename ] && break
    sleep 10
done
Run Code Online (Sandbox Code Playgroud)

对于任何类似 POSIX 的 shell:

n=0
while [ "$n" -lt 10 ] && [ ! -e filename ]; do
    n=$(( n + 1 ))
    sleep 10
done
Run Code Online (Sandbox Code Playgroud)

在再次测试文件是否存在之前,这两个循环在每次迭代中都会休眠 10 秒。

循环完成后,您必须最后一次测试文件是否存在,以确定循环是否由于运行 10 次或文件出现而退出。

如果您愿意,并且可以访问 inotify-tools,您可以将sleep 10调用替换为

inotifywait -q -t 10 -e create ./ >/dev/null
Run Code Online (Sandbox Code Playgroud)

这将等待当前目录中发生文件创建事件,但会在 10 秒后超时。这样,只要给定的文件名出现(如果出现),您的循环就会退出。

完整的代码,带有inotifywaitsleep 10如果你不想要,替换为),可能看起来像

for (( i=0; i<10; ++i)); do
    [ -e filename ] && break
    inotifywait -q -t 10 -e create ./ >/dev/null
done

if [ -e filename ]; then
    echo 'file appeared!'
else
    echo 'file did not turn up in time'
fi
Run Code Online (Sandbox Code Playgroud)