Search code examples
bashfunctionif-statementprompt

bash if "$1" == "0" is always false when running function for bash prompt


I have been struggling with this for a long time. Trying to change colour as part of my prompt depending on the exit code of the last command.

I have reduced my prompt to a minimal example:

Red="\[\033[31m\]"
Green="\[\033[32m\]"
Reset="\[\033[0m\]"

statColour(){
    if [[ "$1" == "0" ]]; then
        echo -e "${Green} $1 "
    else
        echo -e "${Red} $1 "
    fi
}

export PS1="$(statColour \$?)What Colour? $Reset"

And results in red always being used despite the fact the number is clearly 0 in the first instance.

enter image description here

I have tried [ and $1 -eq 0 with no success. Why isn't this working?


Solution

  • Try this:

    Red="\033[35m"
    Green="\033[32m"
    Reset="\033[0m"
    
    statColour(){
        if [[ $1 = 0 ]]; then
            echo -e "${Green} $1 "
        else
            echo -e "${Red} $1 "
        fi
    }
    
    export PS1="\$(statColour \$?)What Colour? $Reset"
    #           ^
    
    1. Color definitions changed
    2. Call of statColour is now done every time, and not only once.
    3. if [[ ]] optimized