Bash IO Redirection – Shell Variable $_ Not Behaving as Expected

bashio-redirection

What the reason the number of lines differs?

$ head -n 100000 ./access.log > ./data/log.sample
$ cat $_ | wc -l
1933424

Best Answer

$_ is expanding to ./access.log (last argument of the last executed command), not ./data/log.sample.

So you are actually seeing the number of lines of ./access.log.

The redirection (>) is not part of the head command as it is done by the shell before the head command is even started. Hence with $_ you would get ./access.log.


From man bash:

($_, an underscore.) At shell startup, set to the absolute pathname used to invoke the shell or shell script being executed as passed in the environment or argument list. Subsequently, expands to the last argument to the previous command, after expansion. Also set to the full pathname used to invoke each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file.

Related Question