Check if the previous command was "valid"

I have a function defined in .bashrc that shows whether the previous command was successfully executed 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 that Command successful displayed immediately when I run the prompt, even if I haven’t "officially" run any commands yet. Secondly (and for the same reason), the script displays Command successful (or the output of the last "real" command), even if all I did was press the return button without actually executing the command ( sample output ).

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

+7
bash .bash-profile
source share
2 answers

As others have already mentioned, there is no need to display so many messages in a message. Below is the Bash hint I'm using:

The screenshot

As you can see, the exit value at the prompt becomes RED when it is nonzero, so you can easily find out that the command just worked. And if the command is killed by a signal, the number and name of the signal will also be displayed. In the above screenshot, 130:2:INT means the last command completed with 130 (= 128 + 2), and it was killed by signal 2 ( SIGINT ).

Below 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] # ' 
+1
source share

One of the easiest ways to do this on the command line is through 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 usually I do it.

0
source share

All Articles