I started a new job in March, and the company sent me a new MacBook. As usual, macOS has Zsh shell preinstalled.
This time, instead of installing Oh My Zsh, I decided to configure Zsh the hard way. I wanted to understand better how it works.
So I started searching online for tutorials and videos about Zsh. Surprisingly, almost every post briefly explains what Zsh is and then moves to Oh My Zsh.
I want to set up a few things on Zsh and not use a bloated framework that can magically transform my shell into a Christmas tree full of light.
To start, I wanted to customise my Zsh prompt.
How to set up your prompt
"PROMPT" is the variable that specifies the style of the prompt.
To show its value, echo it from the shell:
% echo $PROMPT
To change it, assign a different value, for example:
PROMPT=">>> "
It sets >>>
as your prompt in your current shell.
That is only valid for your current session. Indeed, if you open a new shell, you'll see the default prompt.
Add
PROMPT=">>> "
to the ~/.zshrc
to make it permanent.
That's a good start, but it provides little information. Zsh prompt is very flexible. It can show tons of information, supports ternary operator and allows multiple colours. To give you an idea, this is what my current prompt looks like:
√ prj/alessandro-blog main%
You can notice three main parts:
- a green check mark (√) showing whether the last command succeeded. If it fails, the prompt will show a red "Err."
- the current working directory and its parent
- finally, the prompt symbol % or #
The prompt is pretty simple, but the code that generates it is a bit cryptic:
%(?.%F{green}√.%F{red}Err.%?)%f %B%F{240}%2~%f%b %#
Let's see how it works:
- ? is a special shell variable containing the last command's exit code status. Exit status 0 means success and non-zero means failure.
-
%(?.%F{green}√.%F{red}Err.%?)
is a ternary operator. If ? is 0 (success) the text colour will be green. Otherwise, it will be red. I grasped the syntax of it only after reading the docs: Zsh - Conditional Substrings in Prompts - %F{colour} sets the text colour
- %f resets the text colour
- %2 displays two directories, starting from the current one
- ~ substitutes the home folder in the path with the ~ char
- %# is the final part of the prompt. It shows # when the shell has super-user privileges and the % char when it does not.
Another essential info I want to show in my prompt is the Git Branch name. It is a perfect topic for a new post on setting up my shell without Oh My Shell.
Useful resources: