`stdin的test-s在ubuntubash4.4和macosbash4.4上是不同的,有可移植的替代品吗?
我有一个很小的脚本,只要它是打开的,就应该从stdin中读取,但当我在Ubuntu上的bash 4.4(来自Docker映像)和bash 4.4 macOS(与brew一起安装)上运行它时,我会得到不同的行为 剧本是:`stdin的test-s在ubuntubash4.4和macosbash4.4上是不同的,有可移植的替代品吗?,bash,macos,ubuntu,io,posix,Bash,Macos,Ubuntu,Io,Posix,我有一个很小的脚本,只要它是打开的,就应该从stdin中读取,但当我在Ubuntu上的bash 4.4(来自Docker映像)和bash 4.4 macOS(与brew一起安装)上运行它时,我会得到不同的行为 剧本是: $ cat test.sh #!/bin/bash while test -s /dev/stdin; do read A; echo "-- $A --"; done 在macOS上,它可以: $ (echo one; echo two) | ./test.sh -- one
$ cat test.sh
#!/bin/bash
while test -s /dev/stdin; do read A; echo "-- $A --"; done
在macOS上,它可以:
$ (echo one; echo two) | ./test.sh
-- one --
-- two --
$ (echo one; echo two) | ./test.sh
# empty output
在Ubuntu上,它可以:
$ (echo one; echo two) | ./test.sh
-- one --
-- two --
$ (echo one; echo two) | ./test.sh
# empty output
有没有其他方法来测试stdin是开放的和非空的?我也玩过
读取
,但它似乎不便于携带。您可以将所有标准的读取循环更改为此,使其在两个系统上都能工作:
[[ ! -t 0 ]] && while IFS= read -r A; do echo "-- $A --"; done
[!-t0]]
:检查数据是否来自终端
测试:
$> { echo one; echo two; } | ./test.sh
-- one --
-- two --
$> ./test.sh <<< $'abc\nfoo'
-- abc --
-- foo --
$> ./test.sh
$>
$>{echo one;echo two;}./test.sh
--一个--
--两个--
$>./test.sh
我不确定这是否是OP想要的。如果没有输入,您的命令将阻塞。如果我理解正确,那么OP希望/test.sh
立即退出。