Generate .gitignore files with Bash function

No more copy/pasting lines from old .gitignore files

Every Git repo needs a .gitignore file, these often vary from project to project and creating them can be a tedious process.

This process used to, at least for me, involve copy/pasting from previous projects only to end up with a new project-specific Frankenstein-like file. Around a year ago I stumbled upon the site gitignore.io which makes it super simple to generate .gitignore files without resorting to copy/pasting from old projects.

The only problem was that when I start new projects Iā€™ll usually be in my Terminal or editor of choice, and I donā€™t want to switch contexts by going to a website to generate the file.

gitignore.io offers an official and very simple command line utility, thatā€™s documented here - but it doesnā€™t quite do as much as I wanted it to.

Luckily @soerenr sent me a link to this great little Gist by kqr.

I havenā€™t written much Bash besides a couple of small scripts here and there, but I thought I could add one little feature to the original gist by kqr. The ability to append existing .gitignore files.

Here is the full slightly edited function:1

function gi() {
  result=$(curl "http://www.gitignore.io/api/$1" 2>/dev/null)

  if [[ $result =~ ERROR ]]; then
    echo "Query '$1' has no match. See a list of possible queries with 'gi list'"
  elif [[ $1 = list ]]; then
    echo "$result"
  else
    if [[ -f .gitignore ]]; then
      result=`echo "$result" | grep -v "# Created by http://www.gitignore.io"`
      echo ".gitignore already exists, appending"
      echo "$result" >> .gitignore
    else
      echo "$result" > .gitignore
    fi
  fi
}

The code should be fairly self explanatory and straight-forward to understand. To use the function in your Bash shell:

# Add the function to your ~/.bash_profile

# Remember to source your ~/.bash_profile after adding the function
$ source ~/.bash_profile

# Show available keyword types
$ gi list

# Create new, or append to existing, .gitignore file
$ gi sass
  1. I created a PR with my edit and kqr wrote a great suggestion. Iā€™ll update this post with improvement from kqr.Ā