output redirection in UNIX
I am a beginner in UNIX. I am finding some difficulty in input/output redirection.
ls -l >temp
cat temp
Here why temp file is shown in the list and moreover, it is showing 0 characters.
wc temp >temp
cat temp
her开发者_StackOverflow社区e output is
0 0 0 temp
. Why lines, words, characters are 0.
Please help me to undestand this concept.
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 whenls
checks the size oftemp
, it is empty, so it shows up in the list as an empty file.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.
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.
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
精彩评论