Last Updated: October 12, 2018
·
1.432K
· ddk

Use tree with gitignore

tree is a handy terminal program that displays the content in a directory in a tree-like format. But most of the time we are not interested in all the files in a directory. Build files and text editor auto saves can easily clutter tree's output to the point where it is almost unusable.

Fortunately, tree provides the -I flag to ignore files that match a given pattern and we can use the patterns in .gitignore to help tree give sensible results.

Put the following in an executable file in your path (i.e. ~/bin/itree) to make a new command to do just that

#!/bin/sh

tree --prune -I $(cat .gitignore ~/.gitignore | egrep -v "^#.*$|^[[:space:]]*$" | tr "\\n" "|")

Some explanation of what is going on here:

  • cat .gitignore ~/.gitignore pastes the .gitigore in this directory and the one in the current user's home directory together.
  • egrep -v "^#.*$|^[[:space:]]*$" removes bank lines and comments.
  • tr "\\n" "|" replaces newlines with pipes.

The combined effect is telling tree to ignore the logical or of each pattern in both .gitignore files.