
假設我有一個名為 bash shell 腳本Myscript.sh
,需要一個參數作為輸入。
但我希望被呼叫的文字檔的內容text.txt
成為該參數。
我已經嘗試過這個但它不起作用:
cat text.txt | ./Myscript.sh
有沒有辦法做到這一點?
答案1
命令替換。
./Myscript.sh "$(cat text.txt)"
答案2
您可以使用管道輸出作為 shell 腳本參數。
試試這個方法:
cat text.txt | xargs -I {} ./Myscript.sh {}
答案3
要完成@bac0n(恕我直言,這是唯一正確回答該問題的人),這裡有一個短行,它將在腳本參數列表中添加管道參數:
#!/bin/bash
declare -a A=("$@")
[[ -p /dev/stdin ]] && { \
mapfile -t -O ${#A[@]} A; set -- "${A[@]}"; \
}
echo "$@"
使用範例:
$ ./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