我可以使用管道输出作为 shell 脚本参数吗?

Nar*_*rin 49 linux bash shell arguments pipe

假设我有一个 bash shell 脚本Myscript.sh,它需要一个参数作为输入。

但我希望被调用的文本文件的内容text.txt作为该参数。

我试过这个,但它不起作用:

cat text.txt | ./Myscript.sh
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

小智 50

您可以使用管道输出作为 shell 脚本参数。

试试这个方法:

cat text.txt | xargs -I {} ./Myscript.sh {}
Run Code Online (Sandbox Code Playgroud)

  • 有人可以解释一下这个命令是如何工作的吗? (2认同)

Ign*_*ams 38

命令替换

./Myscript.sh "$(cat text.txt)"
Run Code Online (Sandbox Code Playgroud)

  • 这有效,但如果 `cat` 失败,那么 `Myscript.sh` 仍会执行。使用 xargs 进行管道传输可确保执行停止。 (2认同)

小智 6

要完成@bac0n(恕我直言,这是唯一正确回答该问题的人),这里有一个短行,它将在脚本参数列表中添加管道参数:

#!/bin/bash

declare -a A=("$@")
[[ -p /dev/stdin ]] && { \
    mapfile -t -O ${#A[@]} A; set -- "${A[@]}"; \
}

echo "$@"
Run Code Online (Sandbox Code Playgroud)

使用示例:

$ ./script.sh arg1 arg2 arg3
> arg1 arg2 arg3

$ echo "piped1 piped2 piped3" | ./script.sh
> piped1 piped2 piped3

$ echo "piped1 piped2 piped3" | ./script.sh arg1 arg2 arg3
> piped1 piped2 piped3 arg1 arg2 arg3

Run Code Online (Sandbox Code Playgroud)


小智 5

将其通过管道输送到xargs实际命令之前,例如cat text.txt | xargs ./Myscript.sh