【发布时间】:2020-07-18 03:08:15
【问题描述】:
我有一个从命名管道读取命令的脚本:
#! /usr/bin/env bash
host_pipe="host-pipe"
#pipe for executing commands
[ -p "$host_pipe" ] || mkfifo -m 0600 "$host_pipe" || exit 1
chmod o+w "$host_pipe"
set -o pipefail
while :; do
if read -r cmd <$host_pipe; then
if [ "$cmd" ]; then
printf 'Running: %s \n' "$cmd"
fi
fi
done
我运行它并使用命令进行测试:
bash -c "echo 'abcdef' > host-pipe"
bash -c "echo 'abcdef' > host-pipe"
bash -c "echo 'abcdef' > host-pipe"
bash -c "echo 'abcdef' > host-pipe"
然后得到奇怪的输出:
Running: abcdf
Running: abcdef
Running: abcde
Running: abcdf
Running: ace
不知何故,脚本无法读取它从管道中获取的所有字符串?怎么读?
【问题讨论】:
-
你在哪个
bash版本上运行这个?无法在 GNUbashv4.4 上重现此内容 -
几个 nitpicks - 1. 您不必使用子 shell 来写入 fifo,只需
echo 'abcdef' > host-pipe就足够了 2. 也不要使用[ "$cmd" ]进行检查字符串是否为空,您很幸运,该字符串已被引用,但[..]下的未引用字符串可能会产生不良结果。使用[ ! -z "$cmd" ]或[[ $cmd ]]
标签: bash pipe named-pipes