Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show job count in bash prompt only if nonzero

Tags:

linux

bash

shell

A typical prompt in bash in something like:

PS1="\u@\h:\w\$ "

The you can show the number of background jobs using \j, e.g.:

PS1="\u@\h:\w [\j]\$ "

Which is useful, because every now and then I forget I have a stopped job and only notice when it complains if I manually logout from the shell.

However, 95% of the time, the background job count is 0 and showing it in the prompt is superfluous.

How can I show the job count in the prompt, but only if it's nonzero?

like image 659
ʞɔıu Avatar asked Sep 28 '12 20:09

ʞɔıu


2 Answers

You can e.g. do something like this:

PS1='\u@\h:\w $([ \j -gt 0 ] && echo [\j])\$ '
like image 166
Mark Avatar answered Nov 10 '22 06:11

Mark


The accepted answer does not work for me (I have got Bash v4.2.46). It throws an error like this:

[: \j: integer expression expected

I had to use PROMPT_COMMAND to achieve the same functionality:

export PROMPT_COMMAND=__prompt_command
function __prompt_command() {
    local JOBS=$(jobs | wc -l | tr -d 0)
    PS1="\u@\h:\w [${JOBS}]\$ "
}
like image 33
Martin Jiřička Avatar answered Nov 10 '22 06:11

Martin Jiřička