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)
Ign*_*ams 38
命令替换。
./Myscript.sh "$(cat text.txt)"
Run Code Online (Sandbox Code Playgroud)
小智 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)
| 归档时间: |
|
| 查看次数: |
69013 次 |
| 最近记录: |