From Bash's manual (Controlling the Prompt]1):

\j the number of jobs currently managed by the shell.  

\$ If the effective uid is 0, #, otherwise $.

What I'd like is to set PS1 to

[some-string] $

when there are no jobs; and

[some-string]2 $

when there are 2 jobs.

How I could I achieve that?

If possible, the solution could be simple, with only basic Bash expansions and possibly Bash builtins.


I don't think Bash supports conditionals in the prompt (like e.g. screen does, IIRC), but you could use command substitution with \j to add some logic over it.

anyjobs() { [[ "$1" != 0 ]] && echo "[ $1 bg job(s) ] "; }
PS1='$? $(anyjobs \j)\u@\h \w\$ '

That does run a subshell, which involves a fork() in Bash, but I can't see a way around that.

In general, you could avoid the subshell by setting a variable in PROMPT_COMMAND, but I can't see a simple way to get the number of jobs there.

  • Many thx, really helpful. PROMPT_COMMAND? maybe similar to this (unix.stackexchange.com/a/217097/202329), though I cannot solve it currently. – qeatzy May 26 '18 at 11:25
  • @qeatzy, Bash runs whatever code there is in the PROMPT_COMMAND variable before printing each (primary) prompt. So you could set a variable there, and use it in PS1. E.g. something like PROMPT_COMMAND='((i += 3))'; PS1='$i \u@\h \w\$ ' (of course you can also call a function in PROMPT_COMMAND to make it cleaner) – ilkkachu May 26 '18 at 11:31
  • So yeah, pretty much what that answer also does. Though with the 7-line case in there, I'd definitely put it in a function. – ilkkachu May 26 '18 at 11:34
  • indeed, the function solution is cleaner. – qeatzy May 26 '18 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.