Search code examples
bashstdin

Read from a file and stdin in Bash


I would like to know if I can write a shell script that accepts two arguments simultaneously, one from a file and the another one from stdin. Could you give some example please?.

I trying

while read line
   do
   echo "$line"
done < "${1}" < "{/dev/stdin}"

But this does not work.


Solution

  • You can use cat - or cat /dev/stdin:

    while read line; do
      # your code
    done < <(cat "$1" -)
    

    or

    while read line; do
      # your code
    done < <(cat "$1" /dev/stdin)
    

    or, if you want to read from all files passed through command line as well as stdin, you could do this:

    while read line; do
      # your code
    done < <(cat "$@" /dev/stdin)
    

    See also: