views:

61

answers:

3

I am a beginner in UNIX. I am finding some difficulty in input/output redirection.

  1. ls -l >temp

    cat temp

    Here why temp file is shown in the list and moreover, it is showing 0 characters.

  2. wc temp >temp

    cat temp

    here output is 0 0 0 temp. Why lines, words, characters are 0.

Please help me to undestand this concept.

+1  A: 

You cannot write and read from the same file at the same time.

So:

wc file > file # NOT WORKING
# but this works:
wc file > file.stats 
mv file.stats file # if you want that
reto
+3  A: 

When you pipe the output to a file, that file is created, the command is run (so ls lists it as an empty file, and wc counts the characters in the empty file), then the output is added to the file.

… in that order.

David Dorward
+3  A: 
  1. Because ls reads all the names and sorts them before printing anything, and because the output file is created before the command is executed, at the time when ls checks the size of temp, it is empty, so it shows up in the list as an empty file.

  2. When wc reads the file, it is empty, so it reports 0 characters in 0 words on 0 lines, and writes this information into the file after it has finished reading the empty file.

Jonathan Leffler
Ok.. Thanks. But after ls command, temp is not empty. Right? so why wc reads it as empty file?
Happy Mittal
Because when you do `wc temp >temp`, the '>temp' is handled before the command is executed, and that empties the file. Contrast with `wc temp >>temp` which appends.
Jonathan Leffler
Ok.. Thanks alot.
Happy Mittal