1

I want to print exit code of previous command in shell if it failed. So I changed PS1 variable in /etc/bash.bashrc like this:

PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w [$?] \$ '
#_______________________________________________^^^^_____

but it always print the exit code of the previous command. Is there any way to add condition in the template so if $? is equal to 0, it does not print $?

2 Answers 2

5

You can create conditions and expressions inside $() like this:

echo "$( var=2; echo $var)"

in your example you can change PS1 variable like this:

PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w $(
    status=$?; (( status != 0 )) && echo "[$status] "
)\$ '

looks like:

jackman@b7q9bw1:~ $ echo hello
hello
jackman@b7q9bw1:~ $ sh -c 'exit 42'
jackman@b7q9bw1:~ [42] $ 
0

Bash executes the code in the variable PROMPT_COMMAND before printing the prompt. One of the things you can do that is to calculate components of the prompt which are then assembled via the PS1 setting.

PROMPT_COMMAND_set_status () {
  if ((last_status == 0)); then
    PS1_status=
  else
    PS1_status="[$last_status] "
  fi
}
PS1=PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w $PS1_status\$ '
PROMPT_COMMAND='last_status=$?; PROMPT_COMMAND_set_status'

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.