DEV Community

Alvin Bryan
Alvin Bryan

Posted on • Edited on • Originally published at alvin.codes

Show your files and folders with `tree`

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
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
mafflerbach profile image
mafflerbach

You should take a peek on broot, it shows the dirs and subdirs like tree, but you can use fuzzy search and open files and change dirs directly.

Collapse
 
alvinb profile image
Alvin Bryan

Hey, thanks for the suggestion!
I just had a look. It's definitely useful to navigate a new codebase but it's a bit too complicated for me to consider it as a valid alternative to tree.
I like that it respects .gitignore by default though :)