Have a great looking terminal and a more effective shell with Oh my Zsh on WSL 2 using Windows

Now Git, the Azure CLI, and Kubernetes Kubectl are used more and more, the bash prompt is one of the most productive ways to do your daily work. When using Windows, the usage of WSL (2) is a must-have when it comes to having a Linux shell to execute bash scripts. This works nice but with Oh-My-Zsh you can make the command-prompt look- and behave better so you can do your work more efficient.

This blogpost tells you the steps to take to get a prompt on Windows with WSL using Visual Studio Code. Actually, this blog post is a reminder for me. It’s how I have configured the WSL and VS Code. It looks like this:

vscodeohmyzsh

Why use Oh-My-Zsh

Oh-My-Zsh is a plugin that runs on top of ZSHUsing Oh-My-Zsh instead of the default bash prompt has several advantages:

  • Themeable prompts. By default, the robbyrussell theme is configured. There are many themes to choose from: https://github.com/robbyrussell/oh-my-zsh/wiki/Themes. When prompted in a git repo, Zsh shows information about the Git status for example.
  • Advanced command history. Works over shells and even works after reboots. See the whole history with “alt+/”.  Very powerful is searching in history using a partly typed command: for example type az and when you hit your arrow up, it only shows the commands in history which start with az.
  • Spelling correction. Type case insensitive and Zsh finds out what you mean.
  • Auto completion. Type – after a command and tab through the command options.
  • Keybindings. Type bindkey to see all keybindings.
  • Globbing. Is a short expression that lets you filter files. For example:
    ls mydir/**/*.json to have all json files in any directory within mydir.
  • Minimize keystrokes. Here is a cheatsheet to make you type less.
  • Plugin support. By default the Git plugin is already configured. Let’s configure the zsh-syntax-highlighting and zsh-autosuggestions. There are much more plugins which can be found here: https://github.com/robbyrussell/oh-my-zsh/wiki/Plugins or here https://github.com/zsh-users

With the needed knowledge a couple of them should be possible in the bash prompt as well, but Oh-My-Zsh makes it very easy.

This list is not extensive. There are so many possibilities, too many to sum them up here. In short: Using Oh-My-Zsh makes your prompt highly customizable using community-created plugins and themes so it makes your life easier.

Why I’m using VS Code together with the terminal in VS Code

I’m using the prompt a lot, to type and execute commands. Very often I need to execute a command in a script file. Therefore I like to use Visual Studio Code together with the terminal within VS Code. So I have only 1 window open to have both the file and the terminal.

I could use Windows Terminal or Cmder if I would only use the command prompt. But having a file ready to be filled with commands or executing commands which are already in a file, I really like to use Visual Studio Code.

Using Oh-My-Zsh also works in Windows Terminal of course and also if you just open WSL itself. This blogpost shows my personal configuration.

Steps to get the cool prompt

Prerequisite

In Windows:

A. Install Windows Sub System 2 (WSL)

First WSL as described here: https://docs.microsoft.com/en-us/windows/wsl/install-win10

In short:

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

I’m using Ubuntu 18.04 LTS: https://www.microsoft.com/store/apps/9N9TNGVNDL3Q

Second and optionally (but recommended because of speed), install WSL 2: https://docs.microsoft.com/en-us/windows/wsl/wsl2-install

B. Install Visual Studio Code
By downloading it here: https://code.visualstudio.com/docs/?dv=win

C. Install Powerline fonts in Windows
To have a correctly working agnoster theme, it’s needed to download and install the needed fonts.

Open a Powershell command prompt:

git clone https://github.com/powerline/fonts.git --depth=1
cd fonts
.\install.ps1

#clean up
cd ..
rd /S /Q fonts

Installation and configuration steps

1. Open Ubuntu

2. Install Zsh (and curl and git)

sudo apt-get install zsh curl git

3. Install Oh-My-Zsh

sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"

4. Change the Theme to agnoster

sed -i 's/ZSH_THEME="robbyrussell"/ZSH_THEME="agnoster"/g' ~/.zshrc

5. Make the directory more readable by changing the back color to a bit lighter blue

The background of the prompt where the directory part is shown is too dark. Let’s make it light blue:

sed -i '0,/blue/{s/blue/39d/}' ~/.oh-my-zsh/themes/agnoster.zsh-theme

6. Enable autocorrection
It’s disabled by default.

sed -i 's/# ENABLE_CORRECTION="true"/ENABLE_CORRECTION="true"/g' ~/.zshrc

7. Optionally: Enable autosuggestions

Clone the Git repo

git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions

Add the plugin to the list in the oh-my-zsh configuration

nano ~/.zshrc

find the following by scrolling down:

plugins=(
    git
)

make sure it looks like this:

plugins=(
    git
    zsh-autosuggestions
)

Add the following line right under the plugins part to prevent error message: “Insecure completion-dependent directories detected”

ZSH_DISABLE_COMPFIX=true

Save the file with CTRL-X. Enter y and hit enter to save the file to the same filename.

8. Optionally: Enable syntax highlighting

Clone the Git repo

git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
plugins=(
    git
    zsh-autosuggestions
    zsh-syntax-highlighting
)

Make sure you have ZSH_DISABLE_COMPFIX=true configured as explained in step 7.

9. Optionally: Do not show the username in the prompt
Do not show the username if you are working on your local machine as yourself. (working on a remote system as another person does show the username)

Open the .zshrc file to edit it

nano ~/.zshrc

Add the following to bottom the .zshrc file:

prompt_context() {
    DEFAULT_USER="($whoami)"
    if [[ "$USER" != "$DEFAULT_USER" || -n "$SSH_CLIENT" ]]; then
        prompt_segment black default "%(!.%{%F{yellow}%}.)$USER"
    fi
}

10. Optionally: Have the cursor on the next line by default
It’s a personal preference. After this change, the cursor is always on the line just below the fancy prompt.

Search for the following part:

prompt_end() {
    if [[ -n $CURRENT_BG ]]; then
        echo -n " %{%k%F{$CURRENT_BG}%}$SEGMENT_SEPARATOR"
    else
        echo -n "%{%k%}"
    fi
    echo -n "%{%f%}"
    CURRENT_BG=''
}

add \n to the longest line. The result will be this:

prompt_end() {
    if [[ -n $CURRENT_BG ]]; then
        echo -n " %{%k%F{$CURRENT_BG}%}$SEGMENT_SEPARATOR\n"
    else
        echo -n "%{%k%}"
    fi
    echo -n "%{%f%}"
    CURRENT_BG=''
}

11. Fix strange characters in the prompt

The prompt still shows strange characters. Fix it in Visual Studio Code and in the terminal of Ubuntu. To fix it do the following:

11a Configure Visual Studio Code

Open Visual Studio Code and make sure to configure the following settings:
Of course, you can also use one of the other powerline fonts.
The second line makes the WSL the default shell when opening the terminal.

"terminal.integrated.fontFamily": "DejaVu Sans Mono for Powerline",
"terminal.integrated.shell.windows": "C:\\Windows\\System32\\wsl.exe"

Restart VS Code to apply the changes.

11b Configure Ubuntu terminal

Open Ubuntu, click on the Ubuntu logo on the right top and choose for defaults.

Select a Powerline font like DejaVu Sans Mono for Powerline

ohmyzshubuntu

Restart the terminal to apply the changes.

11c Configure Windows Terminal

Choose for the Settings in the Windows Terminal

windowsterminal

Add the following line to the profile of Ubuntu:

"fontFace": "DejaVu Sans Mono for Powerline"
So the result looks like this in profiles.json:
// To view the default settings, hold "alt" while clicking on the "Settings" button.
// For documentation on these settings, see: https://aka.ms/terminal-documentation
{
    "$schema": "https://aka.ms/terminal-profiles-schema",
    "defaultProfile": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
    "profiles":
    [
        {
            // Make changes here to the powershell.exe profile
            "guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
            "name": "Windows PowerShell",
            "commandline": "powershell.exe",
            "hidden": false
        },
        {
            // Make changes here to the cmd.exe profile
            "guid": "{0caa0dad-35be-5f56-a8ff-afceeeaa6101}",
            "name": "cmd",
            "commandline": "cmd.exe",
            "hidden": false
        },
        {
            "guid": "{574e775e-4f2a-5b96-ac1e-a2962a402336}",
            "hidden": false,
            "name": "PowerShell Core",
            "source": "Windows.Terminal.PowershellCore"
        },
        {
            "guid": "{2c4de342-38b7-51cf-b940-2309a097f518}",
            "hidden": false,
            "name": "Ubuntu",
            "source": "Windows.Terminal.Wsl",
            "fontFace": "DejaVu Sans Mono for Powerline"
        },
        {
            "guid": "{b453ae62-4e3d-5e58-b989-0a998ec441b8}",
            "hidden": false,
            "name": "Azure Cloud Shell",
            "source": "Windows.Terminal.Azure"
        }
    ],

    // Add custom color schemes to this array
    "schemes": [],

    // Add any keybinding overrides to this array.
    // To unbind a default keybinding, set the command to "unbound"
    "keybindings": []
}
12. Optionally: Multiple command prompts in VS Code
If you want to be able to have multiple command prompts in Visual Studio Code, then install extension https://marketplace.visualstudio.com/items?itemName=Tyriar.shell-launcherTo have a WSL, Powershell and Powershell Core command prompt add this to the configuration: (Make sure you have installed the Powershell Core Command Prompt before using the exact configuration below):

Add the following settings to VS Code:

"shellLauncher.shells.windows": [
        {

            "shell": "C:\\Windows\\System32\\wsl.exe",
            "label": "WSL Bash"

        },
        {

            "shell": "C:\\Program Files\\PowerShell\\7-preview\\pwsh.exe",            
            "label": "Powershell Core"            

        },
        {

            "shell": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
            "label": "PowerShell"
        }
    ],
Add a short-cut to change the shell:
Add this line to keybindings.json to change shell with ctrl-shift-t
 {
    "key": "ctrl+shift+t",
    "command": "shellLauncher.launch"
}
13. Optionally: Short-cut in VS Code to execute selected line
I also like to have a short-cut to execute the selected line in a file in VS Code:
{
    "key": "f3",
    "command": "workbench.action.terminal.runSelectedText"
}

Conclusion

I like the way of working with Oh-My-Zsh very much. Although I’m still learning to use it every day because it’s so extensive. The full .zshrc script can be seen here

Thanks, Geert van der Cruijsen for reviewing my blog post (and ending up with a cool terminal as well :-))

Geef een reactie

Vul je gegevens in of klik op een icoon om in te loggen.

WordPress.com logo

Je reageert onder je WordPress.com account. Log uit /  Bijwerken )

Google photo

Je reageert onder je Google account. Log uit /  Bijwerken )

Twitter-afbeelding

Je reageert onder je Twitter account. Log uit /  Bijwerken )

Facebook foto

Je reageert onder je Facebook account. Log uit /  Bijwerken )

Verbinden met %s