Warm tip: This article is reproduced from serverfault.com, please click

How to read from a file or STDIN in Bash?

发布于 2011-08-08 09:27:56

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 handy.

Wondering is there an equivalent in Bash?

Questioner
Dagang
Viewed
0
238k 2015-08-20 04:37:09

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.