bash 如何从管道输入或命令行参数中读取

How can bash read from piped input or else from the command line argument

我想从管道或命令行参数(比如 </code>)中读取一些数据,以提供者为准(优先级为管道)。</p> <p>这个片段告诉我管道是否打开,但我不知道在里面放什么才能不阻塞脚本 (<code>test.sh)(使用 readcat)

if [ -t 0 ]
then
    echo nopipe
    DATA=
else
    echo pipe
    # what here?
    # read from pipe into $DATA
fi

echo $DATA

执行上面的 test.sh 脚本我应该得到以下输出:

$ echo 1234 | test.sh
1234
$ test.sh 123
123
$ echo 1234 | test.sh 123
1234

您可以将所有标准输入读入一个变量:

data=$(cat)

请注意,您所描述的是非规范行为。优秀的 Unix 公民将:

  1. 如果作为参数提供,则从文件名读取(无论 stdin 是否为 tty)
  2. 如果没有提供文件则从标准输入读取

这是您在 sedgrepcatawkwcnl 中看到的内容,仅举出一个很少。


无论如何,这是您的示例,其中展示了所请求的功能:

$ cat script 
#!/bin/bash

if [ -t 0 ]
then
    echo nopipe
    data=
else
    echo pipe
    data=$(cat)
fi

echo "$data"

$ ./script 1234
nopipe
1234

$ echo 1234 | ./script
pipe
1234