Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

"ls -l | wc -l" outputs "1+no. file/directories"(extra one for the first line).

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

share|improve this question

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.

share|improve this answer

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.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .