文件轮询的替代方案?

wyc*_*wyc 2 command-line bash terminal shell-script

在下面的代码中,我必须轮询$tmp_input才能继续执行代码,因为wezterm cli send-text它是异步的。这可确保一切$tmp_input准备就绪。

tmp_input=$(mktemp ./tmp_input.XXXXXX)

echo "read input; echo \$input > $tmp_input" | wezterm cli send-text --pane-id $bottom_pane_id --no-paste

while [ ! -s "$tmp_input" ]; do
    sleep 1
done

input_value=$(cat "$tmp_input")
rm "$tmp_input"

echo "Input was: $input_value" | wezterm cli send-text --pane-id $bottom_pane_id --no-paste
Run Code Online (Sandbox Code Playgroud)

该代码有效,但我想知道是否有另一种方法可以实现相同的结果。

mur*_*uru 10

您可以改为创建一个命名管道mkfifo,然后阅读它。读取将被阻塞,直到有东西写入管道为止,无需手动轮询。就像是:

tmp_input=$(mktemp -d ./tmp_input.XXXXXX)
mkfifo "$tmp_input/fifo"

echo "read input; echo \$input > $tmp_input/fifo" | wezterm cli send-text --pane-id $bottom_pane_id --no-paste

input_value=$(cat "$tmp_input/fifo")
rm "$tmp_input/fifo"
rmdir "$tmp_input"

echo "Input was: $input_value" | wezterm cli send-text --pane-id $bottom_pane_id --no-paste
Run Code Online (Sandbox Code Playgroud)

我转而mktemp -d作为一种希望更安全的替代方案,而不是从 获取名称mktemp然后使用该名称mkfifo


Pop*_*pup 5

您听说过inotifywait吗?听起来像是你想要的。

(我经常使用entr来执行文件更改 - 但我认为您可以使用 inotifywait 实现您的目标。)