Quickly add lines to .gitignore using echo in the command line

Today I learned… that you don’t have to open .gitignore in your editor, add a line(s) to it, save it, and close it. You can do all that in one step from the command line using echo!

Here’s a preview:

$ echo '.DS_Store' >> .gitignore

How it works

Here’s a common scenario. You do git status on your working folder and discover git wants to add some file you don’t want added to your remote repository, like the pesky .DS_Store file.

Thanks, but no thanks, git. I don't want that .DS_Store file in my git repository.
Thanks, but no thanks, git. I don’t want that .DS_Store file in my git repository.

If your git project doesn’t already have a .gitignore file, create one in one step by typing this while in your project’s root directory:

$ touch .gitignore

From here, you could open that .gitignore file in an editor and add lines to it, save it and close it, but that’s rather cumbersome if all you need to add is one or a few lines.

Here’s a faster way, using “echo” to push some new data into the file.

$ echo '.DS_Store' >> .gitignore

The double >> is important. If you type just one >, you’ll overwrite the existing contents. Using >> appends your echo string to the end.

For a sanity check, open up .gitignore and you’ll see that .DS_Store has been added.

Once you’re more accustomed to using .gitignore you’ll probably come up with a “boilerplate” .gitignore to copy and paste into all your projects, but you’ll probably never reach a point where you aren’t occasionally surprised by an unwanted file showing up in your git status.

 

7 thoughts on “Quickly add lines to .gitignore using echo in the command line”

  1. Thanks for this very simple and effective post. I’ve been to Stack Overflow looking for this answer and everything I saw there was unnecessarily convoluted. It’s really quite simple – .gitignore is a text file that records the data you want to ignore, which in turn needs to be updated in .git! Wonderful!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.