Suppose that I have a file called temp.txt. Using the cat program, I would like to add the contents of this file to the end of myfile.txt — creating myfile.txt if it does not exist and appending to it if it does.
I am considering these possibilities:
cat temp.txt > myfile.txt
or
cat temp.txt >> myfile.txt
Both commands appear to work as I want. So, my question is, what is the difference between > and >>? Thanks for your time.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
> writes to a file, overwriting any existing contents. >> appends to a file.
From man bash:
Redirecting Output
Redirection of output causes the file whose name results from the
expansion of word to be opened for writing on file descriptor n, or
the standard output (file descriptor 1) if n is not specified. If the
file does not exist it is created; if it does exist it is truncated to
zero size.The general format for redirecting output is:
[n]>wordIf the redirection operator is >, and the noclobber option to the set builtin has been enabled, the redirection will fail
if the file whose name results from the expansion of word exists and
is a regular file. If the redirection operator is >|, or the
redirection operator is > and the noclobber option to the set builtin
command is not enabled, the redirection is attempted even if the file
named by word exists.Appending Redirected Output
Redirection of output in this fashion causes the file whose name
results from the expansion of word to be opened for appending on file
descriptor n, or the standard output (file descriptor 1) if n is not
specified. If the file does not exist it is created.The general format for appending output is:
[n]>>word
Method 2
In case of >
eg. cat abc.txt > pqr.txt
The contents of pqr.txt will be replaced with that of abc.txt
In case of >>
eg. cat abc.txt >> pqr.txt
The contents of abc.txt will be appended with that pqr.txt at the end.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0