Friday, April 8, 2022

[SOLVED] Using echo; What is difference between > and >>

Issue

I came across this on a git site:

mkdir log
echo '*.log' > log/.gitignore
git add log
echo tmp >> .gitignore
git add .gitignore
git commit -m "ignored log files and tmp dir"

So in the first instance of echo, we are writing the string to the file .gitignore in the log dir. In the second instance, are we writing tmp to the file .gitignore (in current dir). Why do we need to use >> versus > ?


Solution

When echoing something to a file, >> appends to the file and > overwrites the file.

$ echo foobar > test
$ cat test
foobar
$ echo baz >> test
$ cat test
foobar
baz
$ echo foobar > test
$ cat test
foobar

From the example you posted, a log directory is created and then *.log is put into log/.gitignore so that no log files are committed to git. Since > was used, if a .gitignore file had existed, it would be overwritten with only *.log.

The log directory itself is then added to your local git stage.

On the next line, >> is added so that tmp is appended to the end of the .gitignore file instead of overwriting it. It is then added to the staging area.



Answered By - castis
Answer Checked By - Marilyn (WPSolving Volunteer)