Introduction to the tree command
From UnixCasts.com (formerly Learning the UNIX command line on OS X)
Hey there!
It’s time for our 7th installment of UNIX command line tips. In the previous newsletter, we talked about curly brace expansion in bash.
This week we're going to shift focus to a useful little utility that I've come to use more often in recent months, which is the tree
command.
The tree command in UNIX
The tree
command, a handy alternative to ls
, is a command which list the contents of directories in a tree-like format. It's really great when you need to view files and directories in a structured manner. In the examples that follow, I’m going to show the directory contents of a plugin for vim called vim-gitgutter, which I find to be very helpful when I work with git repositories.
Installation
On OS X, installation of the tree
command is a breeze when using brew:
brew install tree
Basic usage
Using the vim-gitgutter directory on my local machine, let’s look at a few options that the tree
command offers.
By default, the tree
command displays output based on the current working directory:
☺ tree
.
├── README.mkd
├── doc
│ ├── gitgutter.txt
│ └── tags
├── plugin
│ └── gitgutter.vim
└── screenshot.png
2 directories, 5 files
Alternatively, you can specify a directory argument as well:
☺ tree ~/.vim/bundle/vim-gitgutter
/Users/chip/.vim/bundle/vim-gitgutter
├── README.mkd
├── doc
│ ├── gitgutter.txt
│ └── tags
├── plugin
│ └── gitgutter.vim
└── screenshot.png
2 directories, 5 files
Listing directories only
At times, it's also nice just to view the directory structure using the -d option:
☺ tree -d
.
├── doc
└── plugin
2 directories
Showing human readable file sizes
It's also useful to know that there are options that are more similar to what the ls
command provides, such as when you pass the -h flag for viewing human readable file and directory sizes:
☺ tree -h
.
├── [9.6K] README.mkd
├── [ 136] doc
│ ├── [7.5K] gitgutter.txt
│ └── [1.0K] tags
├── [ 102] plugin
│ └── [ 16K] gitgutter.vim
└── [ 16K] screenshot.png
2 directories, 5 files
Displaying file permissions
There is also the ability to view file and directory permissions using the -p flag:
☺ tree -p
.
├── [-rw-r--r--] README.mkd
├── [drwxr-xr-x] doc
│ ├── [-rw-r--r--] gitgutter.txt
│ └── [-rw-r--r--] tags
├── [drwxr-xr-x] plugin
│ └── [-rw-r--r--] gitgutter.vim
└── [-rw-r--r--] screenshot.png
2 directories, 5 files
There are many more options available for using the tree
command, so next time you need to view a directory in a more structured way, please take a closer look at the man pages for tree
.
For more UNIX tips, please check out UnixCasts.com.