Unix 脚本:等待文件存在

Cid*_*icc 16 unix shell-script

我需要一个脚本来等待 (examplefile.txt) 出现在 /tmp 目录中

一旦发现它停止程序,否则休眠文件直到它被定位

到目前为止,我有:

如果 [ !-f /tmp/examplefile.txt ]

然后

小智 23

until [ -f /tmp/examplefile.txt ]
do
     sleep 5
done
echo "File found"
exit
Run Code Online (Sandbox Code Playgroud)

每 5 秒它会唤醒并查找文件。当文件出现时,它会退出循环,告诉你它找到了文件并退出(不是必需的,但很整洁。)

将其放入脚本并将其作为脚本启动 &

这将在后台运行它。

根据您使用的 shell,语法上可能存在细微的差异。但这就是它的要点。


Eli*_*ley 23

这个 bash 函数将阻塞,直到给定的文件出现或达到给定的超时。如果文件存在,退出状态将为 0;如果没有,退出状态将反映函数等待了多少秒。

wait_file() {
  local file="$1"; shift
  local wait_seconds="${1:-10}"; shift # 10 seconds as default timeout

  until test $((wait_seconds--)) -eq 0 -o -e "$file" ; do sleep 1; done

  ((++wait_seconds))
}
Run Code Online (Sandbox Code Playgroud)

以下是如何使用它:

# Wait at most 5 seconds for the server.log file to appear

server_log=/var/log/jboss/server.log

wait_file "$server_log" 5 || {
  echo "JBoss log file missing after waiting for $? seconds: '$server_log'"
  exit 1
}
Run Code Online (Sandbox Code Playgroud)

另一个例子:

# Use the default timeout of 10 seconds:
wait_file "/tmp/examplefile.txt" && {
  echo "File found."
}
Run Code Online (Sandbox Code Playgroud)

  • 这太酷了,但我只想评论一下“-f”仅适用于_regular_文件。如果您需要等待其他类型的文件,请参阅[此](https://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html)以了解 bash 中的文件条件表达式。 (2认同)