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