An essential tool for any developer is a text-based shell or command-line interface (CLI). Attempting to develop top quality software without making use of a CLI is nigh impossible. These magnificent tools come in various flavours and standards. However, they all share a common goal: to provide instructions to your operating system.
Your choice of shell is largely constrained by the base operating system with UNIX based operating systems providing the largest degree of customisability. Windows users may find themselves stuck to using cmd and Powershell. However, Cygwin, Cmderand the new Ubuntu Subsystem may be utilised to provide temporary relief. More permanent relief is achieved by switching to Ubuntu (or similar) and so the rest of this tutorial assumes Ubuntu is being used.
One particularly excellent shell is Z shell (Zsh). On its own it is already a massive upgrade from bash.
Installing Zsh is made incredibly easy by using a package manager. To install Zsh on Ubuntu run the following in your standard terminal (Ctrl + Alt + T):
sudo apt-get install zsh
Then, verify it has installed correctly:
zsh --version
Installing Zsh is made incredibly easy by using a package manager. To install Zsh on Ubuntu run the following in your standard terminal (Ctrl + Alt + T): sudo apt-get install zsh. Then, verify it has installed correctly: zsh -version. Next we want to set it to our default shell: chsh -s $(which zsh).
Next we want to set it to our default shell:
chsh -s $(which zsh)
That's it, Zsh is now installed and set to your default shell. You may need to logout and log back in for the default shell setting to take effect. Upon opening a terminal again you will be asked some setup questions; select the option which populates your configuration with the default system administrator recommended settings.
Oh My Zsh is an open-source configuration manager for Zsh. Using it vastly improves Zsh and allows you to make your terminal behave, look and feel however you want. To install Oh My Zsh run the following (from their website):
sh -c '$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)'
This command executes an installation shell script retrieved via curl from the master branch of the Oh My Zsh Github repository. This script should manage everything for you and upon completion you should have a beautiful new terminal; another upgrade.
Next up, let's install an Oh My Zsh plugin: zsh-autosuggestions. This plugin is a life-changer and I'm unsure of whether I would be able to develop without it. It suggests in a light gray text what you are going to type based on your command history. This is extremely useful for those tricky grep commands or repetitive Git commands.
To install (based on their Install.md) run the following command (which utilises our previously installed Oh My Zsh):
git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
This command clones the latest version of the plugin to the custom plugins directory of Oh My Zsh using Git.
In order for this plugin to actually be used we need to add it to our .zshrc, the Zsh configuration file. To do this, open ~/.zshrc in your favourite text editor and add zsh-autosuggestions to your plugins array. It should look something like this when you're done:
Close and open another terminal session to see whether it has worked or not.
Your shell should now look something like this:
I hope this tutorial has helped you install and setup an amazing terminal tool. Out of the box, it should already be a vast improvement over almost anything else. The options for further customisation and extension are limitless and I leave that up to the reader to explore. If you find any plugins or themes particularly useful please share in the comment section below.
Zsh is a powerful shell that operates as both an interactive shell and as a scripting language interpreter. While being compatible with the POSIX sh (not by default, only if issuing
emulate sh ), it offers advantages such as improved tab completion and globbing.
The Zsh FAQ offers more reasons to use Zsh.
Installation
Before starting, users may want to see what shell is currently being used:
Install the zsh package. For additional completion definitions, install the zsh-completions package as well.
Initial configuration
Make sure that Zsh has been installed correctly by running the following in a terminal:
Zsh Autosuggestions Color
You should now see zsh-newuser-install, which will walk you through some basic configuration. If you want to skip this, press
q . If you did not see it, you can invoke it manually with:
Note: Make sure your terminal's size is at least 72×15 otherwise zsh-newuser-install will not run.
Making Zsh your default shell
Change your shell to
/usr/bin/zsh . See Command-line shell#Changing your default shell.
Tip: If replacing bash, users may want to move some code from
~/.bashrc to ~/.zshrc (e.g. the prompt and the aliases) and from ~/.bash_profile to ~/.zprofile (e.g. the code that starts the X Window System).
Startup/Shutdown filesTip:
When starting, Zsh will read commands from the following files in this order by default, provided they exist.
See the graphic representation.
Note:
Warning: Do not remove the default one line in
/etc/zsh/zprofile , otherwise it will break the integrity of other packages which provide some scripts in /etc/profile.d/ .
Configure Zsh
Although Zsh is usable out of the box, it is almost certainly not set up the way most users would like to use it. But due to the sheer amount of customization available in Zsh, configuring Zsh can be a daunting and time-consuming experience.
Simple .zshrc
Included below is a sample configuration file. It provides a decent set of default options as well as giving examples of many ways that Zsh can be customized. In order to use this configuration save it as a file named
.zshrc .
Tip: Apply the changes without needing to logout and then back in by running
source ~/.zshrc .
Here is a simple
.zshrc :
Configuring $PATH
Zsh ties the
PATH variable to a path array. They are automatically synchronized. This allows us to easily manipulate PATH by simply modifying the array. See A User's Guide to the Z-Shell for details.
The line
typeset -U PATH path , where the -U stands for unique, instructs the shell to discard duplicates from both $PATH and $path :
Command completion
Perhaps the most compelling feature of Zsh is its advanced autocompletion abilities. At the very least, enable autocompletion in
.zshrc . To enable autocompletion, add the following to your ~/.zshrc :
The above configuration includes ssh/scp/sftp hostnames completion but in order for this feature to work, users must not enable ssh's hostname hashing (i.e. option
HashKnownHosts in ssh client configuration).
For autocompletion with an arrow-key driven interface, add the following to:
To activate the menu, press
Tab twice.
For autocompletion of command line switches for aliases, add the following to:
For enabling autocompletion of privileged environments in privileged commands (e.g. if you complete a command starting with sudo, completion scripts will also try to determine your completions with sudo), include:
Warning: This will let Zsh completion scripts run commands with sudo privileges. You should not enable this if you use untrusted autocompletion scripts.
Note: This special kind of context-aware completion is only available for a small number of commands.
Key bindings
Zsh does not use readline, instead it uses its own and more powerful Zsh Line Editor (ZLE). It does not read
/etc/inputrc or ~/.inputrc . Read A closer look at the zsh line editor and creating custom widgets for an introduction to ZLE configuration.
ZLE has an Emacs mode and a vi mode. If one of the
VISUAL or EDITOR environment variables contain the string vi then vi mode will be used; otherwise, it will default to Emacs mode. Set the mode explicitly with bindkey -e or bindkey -v respectively for Emacs mode or vi mode.
Key bindings are assigned by mapping an escape sequence matching a keypress to a ZLE widget. The available widgets, with descriptions of their actions and their default keybindings, are listed in zshzle(1) § STANDARD WIDGETS and zshcontrib(1) § ZLE FUNCTIONS.
The recommended way to set key bindings in Zsh is by using string capabilities from terminfo(5). For example[1][2]:
History search
You need to set up the
key array and make sure that ZLE enters application mode to use the following instructions; see #Key bindings.
To enable history search add these lines to
.zshrc file:
By doing this, only the past commands matching the current line up to the current cursor position will be shown when
Up or Down keys are pressed.
Shift, Alt, Ctrl and Meta modifiers
xterm-compatible terminals can use extended key-definitions from user_caps(5). Those are combinations of
Shift , Alt , Ctrl and Meta together with Up , Down , Left , Right , PageUp , PageDown , Home , End or Del . Refer to the zkbd source for a list of recommended names for the modifier keys and key combinations.
For example, for
Ctrl+Left to move to the beginning of the previous word and Ctrl+Right to move to the beginning of the next word:
Prompts
Zsh offers the options of using a prompt theme or, for users who are dissatisfied with the themes (or want to expand their usefulness), the possibility to build a custom prompt.
Prompt themes
Prompt themes are a quick and easy way to set up a colored prompt in Zsh. See zshcontrib(1) § PROMPT THEMES for more information about them.
To use a theme, make sure that prompt theme system is set to autoload in
.zshrc . This can be done by adding these lines to:
Available prompt themes are listed by running the command:
For example, to use the
walters theme, enter:
To preview all available themes, use this command:
Manually installing prompt themes
It is possible to install themes manually, without external configuration manager tools. For a local installation, first create a folder and add it to the
fpath array, eg:
Now create a symbolic link of your theme file in this folder:
If instead you wish to install a theme globally, do:
Now you should be able to activate it using:
If everything works, you can edit your
.zshrc accordingly.
Customized prompt
This article or section needs expansion.
Reason: Add a simple colorless
PROMPT example. (Discuss in Talk:Zsh#)
Additionally to a primary left-sided prompt
PS1 (PROMPT , prompt ) that is common to all shells, Zsh also supports a right-sided prompt RPS1 (RPROMPT ). These two variables are the ones you will want to set to a custom value.
Other special purpose prompts, such as
PS2 (PROMPT2 ), PS3 (PROMPT3 ), PS4 (PROMPT4 ), RPS1 (RPROMPT ), RPS2 (RPROMPT2 ) and SPROMPT , are explained in zshparam(1) § PARAMETERS USED BY THE SHELL.
All prompts can be customized with prompt escapes. The available prompt escapes are listed in zshmisc(1) § EXPANSION OF PROMPT SEQUENCES.
Colors
Zsh sets colors differently than Bash, you do not need to use convoluted ANSI escape sequences or terminal capabilities from terminfo(5). Zsh provides convenient prompt escapes to set the foreground color, background color and other visual effects; see zshmisc(1) § Visual effects for a list of them and their descriptions.
Colors can be specified using a decimal integer, the name of one of the eight most widely-supported colors or as a # followed by an RGB triplet in hexadecimal format. See the description of fg=colour in zshzle(1) § CHARACTER HIGHLIGHTING for more details.
Most terminals support the following colors by name:
Color numbers 0–255 for terminal emulators compatible with xterm 256 colors can be found in the xterm-256color chart.
With a correctly set TERM environment variable, the terminal's supported maximum number of colors can be found from the terminfo(5) database using Note:
echoti colors . In the case of 24-bit colors, also check the COLORTERM environment variable with print $COLORTERM . If it returns 24bit or truecolor then your terminal supports 16777216 (224) colors even if terminfo shows a smaller number.
Example
This article or section needs expansion.
Reason: Add an example using a color from the 16–255 range and one with 24-bit color. (Discuss in Talk:Zsh#)
This is an example of a two-sided prompt:
And here is how it will be displayed:
Sample .zshrc files
See dotfiles#User repositories for more.
Tips and tricksAutostart X at login
See xinit#Autostart X at login.
Restore terminal settings after a program exits abnormally
Many programs change the terminal state, and often do not restore terminal settings on exiting abnormally (e.g. when crashing or encountering SIGINT).
This can typically be solved by executing reset(1):
Oh My Zsh Autosuggestion
The following sections describe ways to avoid the need to manually reset the terminal.
The ttyctl command
The ttyctl command can be used to 'freeze/unfreeze' the terminal. To freeze the interactive shell on launch, use the following:
Resetting the terminal with escape sequences
Alternate linedrawing character set can screw up the terminal in a way which ttyctl cannot prevent.
A simple solution is to output the escape sequences that reset the terminal from the
precmd hook function, so that they are executed every time before the prompt is drawn. For example, using the escape sequencee[0me(Be)0017e[?5le7e[0;0re8 :
To test if it works, run:
Remembering recent directoriesDirstack
Zsh can be configured to remember the DIRSTACKSIZE last visited folders. This can then be used to cd them very quickly. You need to add some lines to your configuration file:
Now use
to print the dirstack. Use
cd -<NUM> to go back to a visited folder. Use autocompletion after the dash. This proves very handy if using the autocompletion menu.
Note: This will not work if you have more than one zsh session open, and attempt to
cd , due to a conflict in both sessions writing to the same file.
cdr
cdr allows you to change the working directory to a previous working directory from a list maintained automatically. It stores all entries in files that are maintained across sessions and (by default) between terminal emulators in the current session.
See zshcontrib(1) § REMEMBERING RECENT DIRECTORIES for setup instructions.
Help command
Unlike Bash, Zsh does not enable a built in
help command, instead it provides run-help . By default run-help is an alias to man , it can be either executed manually by prepending it to a command or it can be invoked for the currently typed command with the keyboard shortcuts Alt+h or Esc h .
Since by default it is just an alias to man, it will only work on external commands. To improve its functionality, so that it works on shell builtins and other shell features, you need to use the
run-help function. See zshcontrib(1) for more information on the run-help and its assistant functions.
First load the
run-help function and then remove the existing run-help alias. For convenience help can be aliased to run-help . For example, add following to your zshrc :
Assistant functions have to be enabled separately:
For example,
run-help git commit command will now open the man pagegit-commit(1) instead of git(1).
Persistent rehash
Typically, compinit will not automatically find new executables in the
$PATH . For example, after you install a new package, the files in /usr/bin/ would not be immediately or automatically included in the completion. Thus, to have these new executables included, one would run:
This 'rehash' can be set to happen automatically.[3] Simply include the following in your
zshrc :
On-demand rehash
As above, however pacman can be configured with hooks to automatically request a
rehash , which does not incur the performance penalty of constant rehashing as above. To enable this, create the /etc/pacman.d/hooks directory, and a /var/cache/zsh directory, then create a hook file:
This keeps the modification date of the file
/var/cache/zsh/pacman consistent with the last time a package was installed, upgraded or removed. Then, zsh must be coaxed into rehashing its own command cache when it goes out of date, by adding to your ~/.zshrc :
If the
precmd hook is triggered before /var/cache/zsh/pacman is updated, completion may not work until a new prompt is initiated. Running an empty command, e.g. pressing enter , should be sufficient.
Alternative on-demand rehash using SIGUSR1
As above, however the hook file looks like this:
Warning: This sends SIGUSR1 to all running
zsh instances. Note that the default behavior for SIGUSR1 is terminate so when you first configure this all running zsh instances of all users (including login shells) will terminate if they have not sourced the trap below.
The function trap above can be replaced with a list trap
trap 'rehash' USR1 . See zshmisc(1) § Trap Functions for differences between types of traps.
This method will instantly
rehash all zsh instances, removing the need to press enter to trigger precmd .
Bind key to ncurses application
Bind a ncurses application to a keystroke, but it will not accept interaction. Use
BUFFER variable to make it work. The following example lets users open ncmpcpp using Alt+ :
An alternate method, that will keep everything you entered in the line before calling application:
File manager key binds
Key binds like those used in graphic file managers may come handy. The first comes back in directory history (
Alt+Left ), the second let the user go to the parent directory (Alt+Up ). They also display the directory content.
xterm title
If your terminal emulator supports it, you can set its title from Zsh. This allows dynamically changing the title to display relevant information about the shell state, for example showing the user name and current directory or the currently executing command.
The xterm title is set with the xterm escape sequence
e]2; a . For example:
will set the title to
A simple way to have a dynamic title is to set the title in the
precmd and preexec hook functions. See zshmisc(1) § Hook Functions for a list of available hook functions and their descriptions.
By using Tip:
print -P you can additionally take advantage of Zsh's prompt escapes.
Ubuntu Zsh AutosuggestionsTerminal emulator tab title
Some terminal emulators and multiplexers support setting the title of the tab. The escape sequences depend on the terminal:
Shell environment detection
See a repository about shell environment detection for tests to detect the shell environment. This includes login/interactive shell, Xorg session, TTY and SSH session.
/dev/tcp equivalent: ztcp
Use the
zsh/net/tcp module:
You can now establish TCP connections:
Shortcut to exit shell on partial command line
By default,
Ctrl+d will not close your shell if the command line is filled, this fixes it:
Third-party extensionsConfiguration frameworks
Zsh-autosuggestions
Plugin managers
Fish-like syntax highlighting and autosuggestions
Fish provides very powerful shell syntax highlighting and autosuggestions. To use both in Zsh, you can install zsh-syntax-highlighting, zsh-autosuggestions, and finally source one or both of the provided scripts from your zshrc:
The 'command not found' handlerZsh Autosuggestion
pkgfile includes a Zsh script file that provides a
command_not_found_handler function that will automatically search the official repositories, when entering an unrecognized command.
You need to source the script to enable it. For example:
Note: The pkgfile database may need to be updated before this will work. See pkgfile#Installation for details.
UninstallationZsh Autosuggestions Slow
Change the default shell before removing the zsh package.
Warning: Failure to follow the below procedure may result in users no longer having access to a working shell.
Run following command:
Use it for every user with zsh set as their login shell (including root if needed). When completed, the zsh package can be removed.
Alternatively, change the default shell back to Bash by editing
/etc/passwd as root.
Warning: It is strongly recommended to use vipw(8) when editing
/etc/passwd as it helps prevent invalid entries and/or syntax errors.
For example, change the following:
To this:
See also
Retrieved from 'https://wiki.archlinux.org/index.php?title=Zsh&oldid=632301'
Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |