Bash – How to read from a file or standard input in Bash

bashstdin

The following Perl script (my.pl) can read from either the file in the command line arguments or from standard input (STDIN):

while (<>) {
   print($_);
}

perl my.pl will read from standard input, while perl my.pl a.txt will read from a.txt. This is very handy.

Is there an equivalent in Bash?

Best Answer

The following solution reads from a file if the script is called with a file name as the first parameter $1 and otherwise from standard input.

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

The substitution ${1:-...} takes $1 if defined. Otherwise, the file name of the standard input of the own process is used.