zsh and bash: what to choose

For those who are not familiar with Z Shell, as well as those who are at a crossroads in choosing a shell for everyday tasks, this article is dedicated.
I must say, a lot of materials have already been written about the advantages of zsh. As for this modest note, it is intended to show the reader the capabilities of both shells using concrete examples of configuration files. The emphasis is still on zsh, because in the understanding of the author, bash is usually suitable for use initially, it is better not to use zsh without your own settings at all.
Full author configuration files can be taken from github .

I. The best thing about shell is auto-completion

There is autocompletion in bash too, which in our time will not surprise anyone. Especially good in this sense is bash-completion, which allows you to complement not only the paths to directories, but also efficiently search for packages for installation. If you have not used it before, my advice to you is to install it. Additional settings for this package are not required.

Zsh may surprise you, it really is. Perhaps auto-completion is one of its strengths. Immediately it should be noted that zsh is modular and to expand its capabilities it is necessary to connect or in some cases install the necessary modules. In addition, you can’t do without customization in zsh: modules will need to be included in your .zshrc. Let us turn to practical examples.
For ArchLinux, it’s better to install packages like bash-completion right away, which will allow you to use autocomplete in searching for packages with pacman and AUR: these are zsh-yaourt and zsh-packer. You can find them in the same AUR. Connect our auto completion:

#Включить автодополнение 
autoload -U compinit promptinit 
compinit
promptinit
# Для pacman
[[ -a $(whence -p pacman-color) ]] && compdef _pacman pacman-color=pacman
# Корректировка ввода
setopt CORRECT_ALL
# Если в слове есть ошибка, предложить исправить её
SPROMPT="Ошибка! ввести %r вместо %R? ([Y]es/[N]o/[E]dit/[A]bort) "
# Не нужно всегда вводить cd
# просто наберите нужный каталог и окажитесь в нём
setopt autocd
# При совпадении первых букв слова вывести меню выбора
zstyle ':completion:*' menu select=long-list select=0
zstyle ':completion:*:default' list-colors ${(s.:.)LS_COLORS}


Already not bad, right? Honestly, I was not attracted by the prospect of switching to zsh, since bash was generally fine. But the experiment showed: zsh is very convenient.

II. Hotkeys
As far as I know, in bash hotkeys cannot be changed. However, it is possible that I am wrong. These are the emacs editor keys known to all Linuxsoids. They are taken as a basis and will work on any machine where bash is installed. Of course, no one will forbid you to use the arrows to move between characters or the delete key to delete a character - this is also in bash, and this also does not need to be configured.

Turn to zsh. Yes, as you probably already guessed: in zsh, everything needs to be customized. Of course, it would be scary if we had to configure each key - not at all! You can choose one of two styles, focusing on the more familiar to you: vi mode or emacs mode.
Recommendation: choose emasc to confidently use hot keys on any machine with any shell, in addition, bash is most popular after all - focus on it.
Of course, you can customize individual keyboard shortcuts as you like.
Example:

bindkey '\e[3~' delete-char # del
bindkey ';5D' backward-word # ctrl+left
bindkey ';5C' forward-word #ctrl+right


III. Aliases
It is very convenient to use aliases of various teams. Aliases are great for configuring both bash and zsh. The difference is that in zsh you can use not only commands, but also assign file type extensions to individual applications. How is this useful? With this feature, zsh can even replace your file manager. See for yourself:

# Aliases
alias ls='ls --color=auto'
alias grep='grep --colour=auto'
alias -s {avi,mpeg,mpg,mov,m2v}=mplayer
alias -s {odt,doc,sxw,rtf}=openoffice.org
autoload -U pick-web-browser
alias -s {html,htm}=chromium


Pay attention to the lines starting with alias -s . Now imagine: you are in the directory with documents and among them there is one or more with the extension .html. What do we usually do? Launch the browser, press Ctrl + O, select the file and view it. What do aliases allow in zsh? Just write the name of the document and it will immediately be opened in the browser.
To do this, a separate pick-web-browser

IV module is loaded first . Command History
And, of course, no user will dispute the usability of command history. Here zsh is no different from bash. Set it up:

#  History
# хранить историю в указанном файле
export HISTFILE=~/.zsh_history
# максимальное число команд, хранимых в сеансе
export HISTSIZE=1000
export SAVEHIST=$HISTSIZE
# включить историю команд
setopt APPEND_HISTORY
# убрать повторяющиеся команды, пустые строки и пр.
setopt HIST_IGNORE_ALL_DUPS
setopt HIST_IGNORE_SPACE
setopt HIST_REDUCE_BLANKS


V. Other amenities
There is one curious thing about zsh: the zsh-syntax-highlighting plugin. ArchLinux users can install it from AUR, the rest can be downloaded from the project of the same name on github. Put it, and your terminal emulator will sparkle with new colors.
Initially, it is focused on any terminals - not only supporting 256 colors, so some colors may not look the way we like, but it can be fixed. The main file with color settings is located on the path:
/usr/share/zsh/plugins/zsh-syntax-highlight/highlighters/main/main-highlighter.zsh . But there is no need to edit it directly (thanks, ZyXI for pointing out the error).
Change the colors as you need in .zshrc and activate the plugin.
Example:

# zsh-syntax-highlighting from AUR
typeset -A ZSH_HIGHLIGHT_STYLES
ZSH_HIGHLIGHT_STYLES=(
        'alias'           'fg=153,bold'
        'builtin'         'fg=153'
        'function'        'fg=166'
        'command'         'fg=153'
        'precommand'      'fg=153, underline'
        'hashed-commands' 'fg=153'
        'path'            'underline'
        'globbing'        'fg=166'
)
source /usr/share/zsh/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh


Also in zsh there is a very popular way of packing / unpacking archives. Enter the extract myfile.tar command - unpack the archive, enter the pk tar myfile command - pack the file into the archive of the specified format. It turns out that zsh can replace the archiver?

For unpacking, write in .zhsrc:

# Распаковка архивов
# example: extract file
extract () {
 if [ -f $1 ] ; then
 case $1 in
 *.tar.bz2)   tar xjf $1        ;;
 *.tar.gz)    tar xzf $1     ;;
 *.bz2)       bunzip2 $1       ;;
 *.rar)       unrar x $1     ;;
 *.gz)        gunzip $1     ;;
 *.tar)       tar xf $1        ;;
 *.tbz2)      tar xjf $1      ;;
 *.tbz)       tar -xjvf $1    ;;
 *.tgz)       tar xzf $1       ;;
 *.zip)       unzip $1     ;;
 *.Z)         uncompress $1  ;;
 *.7z)        7z x $1    ;;
 *)           echo "I don't know how to extract '$1'..." ;;
 esac
 else
 echo "'$1' is not a valid file"
 fi
}


To create archives:

# Запаковать архив
# example: pk tar file
pk () {
 if [ $1 ] ; then
 case $1 in
 tbz)       tar cjvf $2.tar.bz2 $2      ;;
 tgz)       tar czvf $2.tar.gz  $2       ;;
 tar)      tar cpvf $2.tar  $2       ;;
 bz2)    bzip $2 ;;
 gz)        gzip -c -9 -n $2 > $2.gz ;;
 zip)       zip -r $2.zip $2   ;;
 7z)        7z a $2.7z $2    ;;
 *)         echo "'$1' cannot be packed via pk()" ;;
 esac
 else
 echo "'$1' is not a valid file"
 fi
}   


VI. Summary
Zsh is very convenient for everyday work and does a good half of the routine for you. But it is worth paying attention to the differences between these two shells. For example, in zsh after for it is mandatory to insert a space, the numbering of arrays in zsh starts with 1, which is completely impossible to understand.
So, if you use shell for everyday work, excluding scripting, use zsh. If you often have to write your own scripts, only bash! However, you can combine.
How to set zsh as the default shell for an individual user:

$ chsh -s /bin/zsh your_user

Also popular now: