LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   pipe output of ls to file (http://www.linuxquestions.org/questions/programming-9/pipe-output-of-ls-to-file-878624/)

takayama 05-03-2011 04:46 PM

pipe output of ls to file
 
Hello
I want to pipe the output of ls in a folder to a file (lets call it test.txt) but when i do so, but when i do ls > test.txt in test.txt there is also test.txt (logical, sense it there, is there anyway to avoid this)

colucix 05-03-2011 04:50 PM

This is the normal behavior: when you redirect the output of a command to a file, first the file (empty) is created then the command is executed and the file populated with its output. To avoid that, just create the file in another location, e.g. in the /tmp directory:
Code:

ls > /tmp/test.txt && mv /tmp/test.txt .

T3RM1NVT0R 05-03-2011 04:55 PM

@ Reply
 
Well it is working as per design and it is not showing you the false information as when you do ls -l > test.txt the file do exist there.

If you want to avoid that you can do other way round. Support you want to do ls -l /root and save the output into a file then do the following:

ls -l /root > /test.txt

This will put the output of ls -l ran on /root to test.txt file located under / provided test.txt file exist there on / else you have to use double redirection to create it

ls -l /root >> /test.txt

TobiSGD 05-03-2011 05:08 PM

Quote:

Originally Posted by T3RM1NVT0R (Post 4345481)
This will put the output of ls -l ran on /root to test.txt file located under / provided test.txt file exist there on / else you have to use double redirection to create it

ls -l /root >> /test.txt

Wrong. Both redirectors will create the file if it doesn't exist. The difference is that the >-redirector will delete the contents of the file when it already exists, while the >>-redirector will append the new text to the existing file without deleting previous content.

T3RM1NVT0R 05-03-2011 06:13 PM

@ Reply
 
Yup thats true. I dont know why I said that even after knowing that it apends after the last line but still it was wrong. You always correct me... :-) Thank you


All times are GMT -5. The time now is 04:20 PM.