Logo with initials

Nifty command lines: tree

──── 2 mins#CLI

This post is part of the Nifty Command Lines series.

The tree command is an easy way to print files and folder structures. Like you see in a lot of tutorials. Running it without arguments will print your files and folders.

~/code-like-the-90s ❯❯❯ tree
.
β”œβ”€β”€ css
β”‚   └── main.css
β”œβ”€β”€ img
β”‚   └── bkg.png
β”œβ”€β”€ index.html
└── script.js

2 directories, 4 files

Ignoring

You can tell it to ignore directories with tree -I [DirectoryName]. In most web scenarios, you’ll want to ignore your npm packages, so tree -I node_modules.

You can exclude more than one folder by separating them with a pipe character.

tree -I 'node_modules|.cache|test_*|public'

This is a must to ignore cache folders, build directories, etc.

Restricting output

The -d flag restricts it to only show your folders and hide files.

~/c/nextjs-app ❯❯❯ tree -d
.
β”œβ”€β”€ pages
β”‚   └── api
β”œβ”€β”€ public
└── styles

4 directories

The -P flag allows you to only show a certain type of files. For example, if you want to list your JavaScript files while ignoring npm packages.

~/my-app ❯❯❯ tree -P '*.js' -I 'node_modules'
.
β”œβ”€β”€ public
└── src
    β”œβ”€β”€ App.js
    β”œβ”€β”€ App.test.js
    β”œβ”€β”€ index.js
    β”œβ”€β”€ serviceWorker.js
    └── setupTests.js

2 directories, 5 files

Finally, you can restrict how deep in the folder structure you want to crawl using the -L flag. tree -L 2 will only go 2 levels deep.

As usual, install it with Homebrew or apt-get: brew install tree or apt-get install tree

There you go! I’ve used this command quite a lot to create documentation or get a sense of a new codebase. I hope it will be useful for you too.

Cheers