What is the difference between ls >
and ls >>
?
I need to understand this for my GCSE computing but don't know what the difference is.
3 Answers
>
& >>
are redirection operators; they transfer output of something, in this case ls
, elsewhere.
If this output goes to a file, >
will truncate the file - ie delete any previous content, whereas >>
will append new data onto the end of the file, keeping previous content.
This will work with any input, so echo
& cat
, for example, can also be used this way.
Also of interest is the |
operator, which passes the data to another application - so ls | cat -n
will give you a line-numbered listing !
Pipes is the relevant term.
-
2
-
2@DKBose from
strace
output forbash -c 'echo a > blah'
:open("blah, O_WRONLY|O_CREAT|O_TRUNC, 0666)
, so truncate would be the right term.– muruDec 8, 2014 at 17:53 -
"pipes" and also "output redirection", which you sort of used in your answer. Well done. Dec 9, 2014 at 1:57
-
found what I meant: In addition to this nice answer, please see the 2nd (and most upvoted) answer on stackoverflow.com/a/984761/1841533 : using
>>
to write to a file (ex: a log) also has the nice side effect to not have "Nul" chars appear at the beginning of saif file if the file is truncated while the process still write to it! (ex: during log file rotation). Because "foo > file" doesn't seek, it doesn't notice the size change and still points further than the beginning, ad the OS fills with Nul.foo >>file
seeks and therefore points to the new position (the beginning). Dec 9, 2014 at 18:03
The symbols >
and >>
are used to redirect output to a file.
Both will create the file if file does not exist. If the file already exists, then >
will overwrite the file where as >>
will append the data to the file.
So ls > myfile
will create a document named myfile
if it doesn't exist. If myfile
is already present and contains some data, then it will be overwritten with the new data you pass it.
Whereas ls >> myfile
will create a file if doesn't exist and write data to it. If the file exist with some data, then new data gets added to its end.
IF you use a single >, then it will overwrite the file if it already exists. Be very careful when you use this one.
If you use two >>, then it will just append (in other words, start writing at the bottom of the file) if it already exists. Otherwise, it creates a new file if it doesn't exist.
-
1
man bash
).