在 POSIX sh 中,当输入是连续的(事件观察器)时,如何保留在 'while read' 循环中设置的变量?

In POSIX sh, how to preserve variables set in a 'while read' loop when the input is continuous (event watcher)?

如果不需要设置全局变量,或者愿意使用命名管道,可以使用:

$NAMED_PIPE="/tmp/mypipe"
mkfifo $NAMED_PIPE

command | # piped into while read, command can be an event watcher
    while read -r foo bar; do
        MY_VAR="$foo"
        echo "$MY_VAR" # This works
        echo "MY_VAR" > "$NAMED_PIPE" &
    done

echo "$MY_VAR" # This doesn't work
cat "$NAMED_PIPE" # This works

如果需要设置全局变量,可以在bash中使用如下:

while read -r foo bar; do
    MY_VAR="$foo"
    echo "$MY_VAR" # This works
done < <(command) # command can be an event watcher

echo "$MY_VAR" # This works

在POSIX sh中,可以进行如下操作,但对连续输入不起作用(好像只是挂了):

while read -r foo bar; do
    MY_VAR="$foo"
    echo "$MY_VAR" # Works as long as command doesn't produce continuous output
done <<-EOF
$(command) 
EOF

echo "$MY_VAR" # Works as long as command doesn't produce continuous output

在 POSIX sh 中是否有可靠的方法来解析事件观察器(例如 xev、xprop -spy)并能够设置全局变量?命名管道似乎很难便携和安全地使用。

命名管道是解决方案,但您用错了地方。

NAMED_PIPE="/tmp/mypipe"
mkfifo "$NAMED_PIPE"

command > "$NAMED_PIPE" &

while read -r foo bar; do
    MY_VAR="$foo"
    echo "$MY_VAR"
done < "$NAMED_PIPE"

echo "$MY_VAR"