How to read from a file or STDIN in Bash?

Dagang picture Dagang · Aug 8, 2011 · Viewed 348.4k times · Source

The following Perl script (my.pl) can read from either the file on the command line args or from STDIN:

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

perl my.pl will read from STDIN, while perl my.pl a.txt will read from a.txt. This is very convenient.

Wondering is there an equivalent in Bash?

Answer

Fritz G. Mehner picture Fritz G. Mehner · Aug 12, 2011

The following solution reads from a file if the script is called with a file name as the first parameter $1 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.