0

I'd like to incorporate the trick where I show the error code of the last command in my shell prompt. I've tried it - however it always only returns zero no matter what I ran.

Say I set the prompt to this:

export PS1="$? $ "

I get this output when I try typing correct and incorrect input:

0 $    
0 $ echo foo
foo
0 $ echo $?
0
0 $ echofoo
bash: echofoo: command not found
0 $ echo $?
127
0 $ 

So the error code is captured, but not displayed on the shell prompt. I would expect that when I ran echofoo, the next command line would show 127 $, but it shows 0.

This happens too when I try running code which exits non-zero, e.g. this bad.py Python file:

import sys
sys.exit(1)

0 $ python bad.py
0 $ echo $?
1
0 $    

Again, I can see that it exits non-zero, but the shell prompt doesn't reflect that.

How can I correctly display the error code of the previous command in the shell prompt? I would like to know the answer for both bash and tcsh, as I haven't managed to get this working in either shell.

kvantour
  • 25,269
  • 4
  • 47
  • 72
Lou
  • 2,200
  • 2
  • 33
  • 66
  • The immediate problem is that using double quotes causes the _current_ value of `$?` to be frozen in the prompt you set. You want the variable to be evaluated when you display the prompt, not when you originally set the prompt. – tripleee Sep 14 '21 at 10:54
  • As an aside, `PS1` is probably already `export`ed so there should be no reason to do it again. – tripleee Sep 14 '21 at 10:54
  • What do you do to evaluate the variable on display, @tripleee? – Lou Sep 14 '21 at 11:01
  • Trivially, use single quotes instead of double when setting it. – tripleee Sep 14 '21 at 11:07

0 Answers0