Open Source

Learn the power features of zsh

Vincent Danen describes some of the features of the Z shell, such as tab-completion and prompt-handling.

The Z Shell (zsh) is a power-shell that is not often used by many Linux users. The reason for this is that most Linux distributions install, and make default, the bash shell. zsh is packaged for virtually every Linux distribution and installation is usually an apt-get, urpmi, or yum away.

One of the great features of zsh is tab-completion; it also handles all the logistics of tab-completion and is extremely easy to implement, just by adding two lines to your ~/.zshrc file:

autoload -U compinit

The compinit function is what loads the tab-completion system by defining a shell function for every utility that zsh is able to tab-complete. By using autoload, you can optimize zsh by telling it to defer reading the definition of the function until it's actually used, which speeds up the zsh startup time and reduces memory usage.

Using the setopt command, you can configure over 150 different options that impact how zsh works. For instance:

setopt autocd

The line above will allow you to change directories simply by typing the name of the directory (no need to use cd). Or, you might wish to use more powerful globbing or pattern matching features, which can be done by adding the line below to ~/.zshrc:

setopt extended_glob

The various zsh options that can be set with setopt are documented in the zshoptions manpage:

$ man zshoptions

Note that the ~/.zshrc file is sourced for both interactive and login shells. If you want, to set options for when zsh is run non-interactively (i.e., via a cronjob), then you'll want to add those to ~/.zshenv.

Another nice feature with zsh is how it handles prompts. These can be custom or they can be loaded via zsh's prompt system, which contains a number of "stock" prompts that might be suitable. For instance, to use the prompt system enter:

autoload -U promptinit
prompt fire

To list the available fonts, on the command-line, enter "prompt -l". To define your own prompt, use the $PS1 variable, but zsh uses different format specifiers than bash, so a nice prompt might look like:

PS1=$'%{\e[1;32m%}%n@%m%{\e[0m%}:%B%~/%b >%# '

The resulting prompt looks like:

joe@odin:~/ >%

with the user and hostname in bright green.

Delivered each Tuesday, TechRepublic's free Linux NetNote provides tips, articles, and other resources to help you hone your Linux skills. Automatically sign up today!

About Vincent Danen

Vincent Danen works on the Red Hat Security Response Team and lives in Canada. He has been writing about and developing on Linux for over 10 years and is a veteran Mac user.

Editor's Picks

Free Newsletters, In your Inbox