1

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.

1 Answer 1

2

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.

4
  • Many thx, really helpful. PROMPT_COMMAND? maybe similar to this (unix.stackexchange.com/a/217097/202329), though I cannot solve it currently. Commented May 26, 2018 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) Commented May 26, 2018 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. Commented May 26, 2018 at 11:34
  • indeed, the function solution is cleaner. Commented May 26, 2018 at 11:35

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.