BASH - 在变量中存储stdin引用'& 0'

时间:2013-10-14 13:08:48

标签: bash redirect stdin

尝试从文件或标准输入读取,我希望这样做:

if [ "$1" == "-" ]
  then 
    INPUTFILE="&0"
fi

但如果我这样做

while read ROW
  do
    # ... something
done <$INPUTFILE

我得到了

&0: No such file or directory

从命令行

cat <&0

完美地工作,有没有办法将stdin引用存储在变量中? PS:我知道同样的结果可以用一种简单的方式实现......

3 个答案:

答案 0 :(得分:4)

cat有时会使用它,这可能就是其中之一:

# Use cat so it works if $1 is just -
cat $1 |
while read ROW
do
    ...whatever
done

记录您使用cat的原因;否则,它看起来像UUOC(无用的猫)。

答案 1 :(得分:2)

它不起作用,因为shell将&0解释为文件名。

而不是说:

INPUTFILE="&0"

说:

INPUTFILE="/proc/$$/fd/0"

这将使其从当前shell进程的STDIN读取。

答案 2 :(得分:0)

&0不是文件名,但它是使用文件描述符进行I / O重定向的表示法的一部分:您应该将<&0作为一个整体阅读。

您可以在this document中找到更多详情。