【发布时间】:2014-11-01 05:18:29
【问题描述】:
为什么 cat 退出 shell 脚本,但只有当它由管道提供时?
以这个名为“foobar.sh”的shell脚本为例:
#! /bin/sh
echo $#
echo $@
cat $1
sed -e 's|foo|bar|g' $1
还有一个名为“foo.txt”的文本文件,它只包含一行:
foo
现在,如果我在命令行中输入 ./foobar.sh foo.txt,那么我会得到这个预期的输出:
1
foo.txt
foo
bar
但是,如果我输入 cat foo.txt | ./foobar.sh,那么令人惊讶的是我只会得到这个输出:
0
foo
我不明白。如果$# 报告的参数数量为零,那么cat $1 怎么还能返回foo?而且,既然如此,为什么 sed -e 's|foo|bar|g' $1 不返回任何东西,因为显然 $1 是 foo?
这看起来很像一个错误,但我假设它是魔法。请解释!
更新
根据给定的答案,以下脚本给出预期的输出,假设是一行 foo.txt:
#! /bin/sh
if [ $# ]
then
yay=$(cat $1)
else
read yay
fi
echo $yay | cat
echo $yay | sed -e 's|foo|bar|g'
【问题讨论】: