Perl的钻石操作员:可以用bash完成吗?

Ste*_*wig 4 unix bash shell perl diamond-operator

是否有一种惯用的方式来模拟Perl在bash中的钻石操作符?与钻石运营商,

script.sh | ...
Run Code Online (Sandbox Code Playgroud)

读取stdin的输入和

script.sh file1 file2 | ...
Run Code Online (Sandbox Code Playgroud)

读取file1和file2的输入.

另一个约束是我想在script.sh中使用stdin来输入我自己的脚本以外的其他东西.下面的代码执行我想要的file1 file2 ... case,但不适用于stdin上提供的数据.

command - $@ <<EOF
some_code_for_first_argument_of_command_here
EOF
Run Code Online (Sandbox Code Playgroud)

我更喜欢Bash解决方案,但任何Unix shell都可以.

编辑:为了澄清,这是script.sh的内容:

#!/bin/bash
command - $@ <<EOF
some_code_for_first_argument_of_command_here
EOF
Run Code Online (Sandbox Code Playgroud)

我希望这个工作方式与钻石运算符在Perl中的工作方式相同,但它现在只处理文件名作为参数.

编辑2:我不能做任何事情

cat XXX | command
Run Code Online (Sandbox Code Playgroud)

因为命令的stdin 不是用户的数据.命令的stdin是here-doc中的数据.我希望用户数据进入我脚本的stdin,但它不能是我脚本中命令调用的标准输入.

Don*_*rve 6

当然,这是完全可行的:

#!/bin/bash
cat $@ | some_command_goes_here
Run Code Online (Sandbox Code Playgroud)

然后,用户可以在没有参数(或" - ")的情况下调用脚本来读取stdin或多个文件,所有这些文件都将被读取.

如果要处理这些文件的内容(例如,逐行),您可以执行以下操作:

for line in $(cat $@); do
    echo "I read: $line"
done
Run Code Online (Sandbox Code Playgroud)

编辑:由于有用的注释,更改$*$@处理文件名中的空格.

  • 使用"$ @",它将所有参数作为单独的字符串引用. (2认同)