Making Linux shell prompt show last return value
It seems bash
is Xubuntu's default shell.
Edit .bashrc
or .bash_profile
(depending on your system configuration) and look for a line starting with PS1=
. This line sets your prompt.
To add the last command's return value, add the following to that line:
`echo -n $?`
so it looks e.g. like the following (my current prompt, simplified):
PS1='\u in \w (`echo -n $?`)\n -> \$ '
It will look like this, with _
being the cursor:
danielbeck in ~ (0)
-> $ _
Alternatively, you can use the environment variable PROMPT_COMMAND
to prepend the return code to your prompt:
export PROMPT_COMMAND='RET=$?; echo -n "($RET) "'
This will add e.g. (0)
just before your otherwise not modified prompt.
You get the "counter" by adding \#
to your prompt: it's the command number. More useful might be the history number, which doesn't start at 1, but allows you to execute any command by entering an exclamation mark, followed by the command's history number:
984 $ foo
-bash: foo: command not found
985 $ !984
foo
-bash: foo: command not found
986 $ _
After some additional playing:
PS1='`RET=$?; if [ $RET != 0 ] ; then echo "rc $?"; fi`\n\u in `pwd`\n#\# !\! \$ '
This will only show the return value if it's non-zero, on it's own line. The command number and history number are on the same line as the command you're going to enter:
danielbeck in /Users/danielbeck/Downloads
#1 !984 $ foo
-bash: foo: command not found
rc 127
danielbeck in /Users/danielbeck
#2 !985 $ _
The variable $?
contains the exit code for the last run program.
ninth:~ sakkaku$ echo Hello World
Hello World
ninth:~ sakkaku$ echo $?
0
ninth:~ sakkaku$ cat asdasd
cat: asdasd: No such file or directory
ninth:~ sakkaku$ echo $?
1
I think you can get the "number of commands executed" by using an incrementer
ninth:~ sakkaku$ echo $[numcommands++]
0
ninth:~ sakkaku$ echo $[numcommands++]
1
ninth:~ sakkaku$ echo $[numcommands++]
2
ninth:~ sakkaku$ echo $[numcommands++]
3
Then you will need to modify the PS1/PS2 variable in your .bashrc to change the prompt. This seems like a decent guide (except it recommends modifying /etc/bashrc, I would just do ~/.bashrc).