Could someone explain to me the difference between >
and >>
when using shell commands?
Example:
ps -aux > log
ps -aux >> log
It seems the result is the same either way.
Could someone explain to me the difference between >
and >>
when using shell commands?
Example:
ps -aux > log
ps -aux >> log
It seems the result is the same either way.
>
is used to overwrite (“clobber”) a file and >>
is used to append to a file.
Thus, when you use ps aux > file
, the output of ps aux
will be written to file
and if a file named file
was already present, its contents will be overwritten.
And if you use ps aux >> file
, the output of ps aux
will be written to file
and if the file named file
was already present, the file will now contain its previous contents and also the contents of ps aux
, written after its older contents of file
.
if you write in terminal
ps aux > log
It will put the output of ps aux
to log named file.
then if you put
ps aux >> log
then the next output will be appended below the first. if you put only one >
it will overwrite the previous file.
Yes, >>
appends, >
always overwrites/destroys the previous content.
ps -aux > log
is the same as
rm log 2>/dev/null
ps -aux >> log
On Wintel it is the same for .bat
, .cmd
and .ps1
scripts too; common heritage, common sense.
Most important difference is that >
makes shell open a file or file-like object with O_WRONLY|O_CREAT|O_TRUNC
flags - the file will be created or truncated if it exists, while >>
opens file with O_WRONLY|O_CREAT|O_APPEND
flags - file will be created or appended to if it exists. This is evident if you trace system calls, for example with
$ strace -e open,dup2 bash -c 'true >> /dev/null'
...
open("/dev/null", O_WRONLY|O_CREAT|O_APPEND, 0666) = 3
dup2(3, 1) = 1
dup2(10, 1) = 1
And with
$ strace -e open,dup2 bash -c 'true > /dev/null'
...
open("/dev/null", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
dup2(3, 1) = 1
dup2(10, 1) = 1
+++ exited with 0 +++
Notice that in both cases the file descriptor of the open file is duplicated onto file descriptor 1 ( stdout ) of the command, and that will be inherited by whatever command the shell forks.