Can I use pipe output as a shell script argument?
Solution 1:
Command substitution.
./Myscript.sh "$(cat text.txt)"
Solution 2:
You can use pipe output as a shell script argument.
Try this method:
cat text.txt | xargs -I {} ./Myscript.sh {}
Solution 3:
To complete @bac0n which IMHO is the only one to correctly answers the question, here is a short-liner which will prepend piped arguments to your script arguments list :
#!/bin/bash
declare -a A=("$@")
[[ -p /dev/stdin ]] && { \
mapfile -t -O ${#A[@]} A; set -- "${A[@]}"; \
}
echo "$@"
Example use :
$ ./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
Solution 4:
If you have more than one set of arguments in the file (for multiple calls), consider using xargs or parallel, e.g.
xargs -d '\n' Myscript.sh < text.txt
parallel -j4 Myscript.sh < text.txt
Solution 5:
By reading stdin with mapfile you can re-set the positional parameters.
#!/bin/bash
[[ -p /dev/stdin ]] && { mapfile -t; set -- "${MAPFILE[@]}"; }
for i in "$@"; do
echo "$((++n)) $i"
done
$ cat test.txt | ./script.sh
1 first
2 second line
3 third