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?
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.
Nice, it works. Another question is why you add a quote for it? "${1:-/proc/${$}/fd/0}"
The filename you supply on the command line could have blanks.
Is there any difference between using
/proc/$$/fd/0
and/dev/stdin
? I noticed the latter seems to be more common and looks more straightforward.Better to add
-r
to yourread
command, so that it doesn't accidentally eat\
chars; usewhile IFS= read -r line
to preserve leading and trailing whitespace.@NeDark: That's curious; I just verified that it works on that platform, even when using
/bin/sh
- are you using a shell other thanbash
orsh
?