IQAndreas
IQAndreas

Reputation: 8468

Check if the previous command was "valid"

I have a function defined in .bashrc that displays whether or not the previous command completed successfully or not (simplified from the full version):

function previous_command_status()
{
    if [ $? -eq 0 ]; then
        echo "Command successful"
    else
        echo "Command failed with exit code $exit_code"
    fi
}

PROMPT_COMMAND="previous_command_status"

The problem is, Command successful gets displayed immediately when I start the prompt, even if I haven't "officially" run any commands yet. Second (and for the same reason), the script displays Command successful (or the output of the last "real" command) even if all I did was hit the return button without actually executing a command (example output).

How I can get the script to only display the message if a command was actually run?

Upvotes: 8

Views: 1890

Answers (2)

Nick Ellis
Nick Ellis

Reputation: 1077

One of the simplest ways to do this on the command line is with logical operators.

cmd && echo success # this will not print if cmd fails
cmd || echo command failed # this will only print if cmd fails
cmd1 && echo success || echo fail # this will print fail or success depending on outcome

Naturally you might want something more substantial in a script, but this is usually how I go about doing this.

Upvotes: 1

pynexj
pynexj

Reputation: 20688

As mentioned by others it's no need to display so long a message in the prompt. The following is the Bash prompt I'm using:

The screenshot

As you can see the exit value in the prompt becomes RED when it's non-zero so you can easily know that the command just failed. And if the command is killed by a signal the signal number and name will also be displayed. In the above screenshot, 130:2:INT means the last command exited with 130 (= 128 + 2) and it was killed by signal 2 (SIGINT).

The following is the code in bashrc:

function _PS1_command()
{
    local lastexit=$?
    local ESC=$'\033'

    (( lastexit )) && g_PS1_Qcolor="$ESC[1;31m" || g_PS1_Qcolor=

    g_PS1_signal=
    if (( lastexit > 128 )) && kill -l $(( lastexit - 128 )) > /dev/null
    then
        (( g_PS1_signal = lastexit - 128 ))
        g_PS1_signal="$g_PS1_signal:$( kill -l $g_PS1_signal )"
    fi

    return $lastexit
}

PROMPT_COMMAND=_PS1_command
PS1='[\w $g_PS1_Qcolor$?${g_PS1_signal:+:}$g_PS1_signal\e[0m] # '

Upvotes: 2

Related Questions