Using a Mac Equivalent of Unix “tree” Command to View Folder Trees at Terminal
Mac users who come from a unix background may appreciate knowing how to implement the equivalent to the Unix “tree” command in macOS and Mac OS X. There are actually a few different ways to show a folder tree in the Terminal of Mac OS X, we’ll cover an easy tree equivalent achieved through an alias, as well as how to install native ‘tree’ on a Mac just like what you see in Ubuntu or elsewhere in Linux.
This is obviously aimed at command line users, but if you spend more time in the Finder of the Mac you might appreciate listing files and folder contents recursively there, which can be similar but is obviously not displaying a directory tree at the Terminal.
Make a tree Equivalent to View Folder Trees in Terminal for Mac OS X
A simple alias will allow you to view folder trees from the command line of Mac OS:
- Launch Terminal or iTerm if you haven’t done so already
- Open your .bashrc or .zshrc profile in your preferred text editor, we’re using nano because nano is easy:
- On a new line, paste the following alias:
- Hit Control+O and Control+X to save and exit out of nano (or quit from vim or emacs as usual), your tree command for printing directory trees is now ready to use
alias tree="find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'"
Open a new Terminal or reload your Terminal profile and you’re ready to use the new tree alias.
Showing Directory Tree Structure with ‘tree’ on the Mac
Now that you have your alias implemented, you can use the ‘tree’ command to show the hierarchical structure of the present working folder or directory at the command line. For example, if you’re in the root / of a Mac and hit ‘tree’, you will display the hierarchical structure of everything on the Mac (this will take a while and is not recommended, but offers a demonstration of how it works)
The tree command is really best used in subdirectories with some level of containment otherwise you’ll be dumping the structure of the entire filesystem outward from the present working directory.
Installing ‘tree’ for the Mac Command Line
If you want a little more control over ‘tree’ like the ability to specify a directory, or you just want the exact ‘tree’ equivalent that comes from the unix world, you can use homebrew or macports to install tree directly in macOS and Mac OS X:
Installing ‘tree’ with Homebrew:
brew install tree
Installing ‘tree’ with MacPorts:
sudo port install tree
My preference is towards Homebrew but use whichever works for you. Once installed from either, typing ‘tree’ will display the folder tree of any directory on the Mac.
Note to avoid conflict, you won’t want to use a tree alias in the first step and then also install the tree command. You can implement both, but you’d probably want to rename the alias to ‘treed’ or something similar.