
„ls -l | wc -l“ gibt „1+Anzahl Dateien/Verzeichnisse“ aus (eine zusätzliche für die erste Zeile).
However when I run the command ls -l | wc -l > temp (when output is redirected to a new file temp). The value stored in temp file is 1 more than the value which was outputted without redirection. I guess it is because of the new "temp" file created but the temp file should have been created after the ls -l command was run and thus, the output should be the same as the output without redirection.
Someone please help
Antwort1
This is perfectly normal behavior.
What happens is that the shell (sh, bash, csh, ksh, whatever) first reads the entire command line.
Then constructs the processes, pipes and redirection file(s) in right to left order and only then runs the actual commands.
So the redirection file (temp) is created BEFORE the ls command is run.
It has to be, because the file-handle associated with "temp" needs to be available to be used as destination for the wc output, before wc is actually started.
The wc command in turn needs to be setup, before the output of ls can be attached to the filehandle that will be the input for wc.
Although it seems a bit unlogical at first this makes perfect sense when you understand the way shells construct their command sequence.
Antwort2
The shell actually creates the temp
file before it starts running the commands, so you'll always see the temp
file counted. If you don't want it counted, put the temp file somewhere else, like maybe in /tmp
. Or just subtract one from the count you get.