Search code examples
terminalzshoh-my-zshzshrcterminal-emulator

Conditional ZSH_THEME by terminal


I'm trying to make that when .zshrc when invoked chooses a specific theme based on which terminal amulator i'm running. For this I came up with:

current_terminal="$(ps -p$PPID -o cmd=)"

function choose_theme {
        if [ $current_terminal=~'tilix' ];
        then echo 'powerlevel9k/powerlevel9k';
        else echo 'robbyrussell';
        fi
}

ZSH_THEME="$(choose_theme)"

I don't get any error message when running and when I open on tilix it works just fine with the powerlevel9k theme, but just that, it doesn't seem to respect the condition and I don't know where might my mstake be =/

The output for the variable current_terminal in each terminal emulator i'm using are:

Tilix:

/usr/bin/tilix --gapplication-service

Default Terminal:

/usr/lib/gnome-terminal/gnome-terminal-server

So it's getting things wright, but setting up always the first option for some reason


Solution

  • This does not work due to two reasons:

    1. You are using [ ... ] instead of [[ ... ]] for the check. The difference is that [[ ... ]] is part of the ZSH's syntax and [ (aka test) is a built-in command that tries to emulate the external test program. This matters because [ does not support the =~ operator, it is only available inside [[ ... ]].

    2. The =~ (like any other operator) needs to be surrounded by white spaces. As a Unix shell ZSH tokenizes command on white spaces. In this case ZSH I would guess that ZSH only checks whether $current_terminal=~'tilix' evaluates to a non-empty string instead of comparing $current_terminal to 'tilix'. This is always the case, hence why you always get the powerlevel9k theme.

    So the condition should look like this:

    current_terminal="$(ps -p$PPID -o cmd=)"
    
    function choose_theme {
        if [[ $current_terminal =~ 'tilix' ]];
        then echo 'powerlevel9k/powerlevel9k';
        else echo 'robbyrussell';
        fi
    }
    
    ZSH_THEME="$(choose_theme)"