16

I'm customizing my zsh prompt and have found the following to check if there are any background jobs:

if [[ $(jobs | wc -l) -gt 0 ]]; then # has background job(s)
    number_jobs='J:${cyan}%j${no_color}'
else # no background job(s)
    number_jobs=""
fi

The problem I'm facing is that the code appears to be evaluated only when I open a new session rather than after each command making this rather useless. How can I have number_jobs re-evaluated after each command?

Abizern
  • 146,289
  • 39
  • 203
  • 257

1 Answers1

33

zsh has a special prompt sequence, like C ternary operator. The below construction means if there are one or more jobs then print their number or print nothing:

 %(1j.%j.)
yazu
  • 4,462
  • 1
  • 20
  • 14
  • Does the 1j portion state "if there is one job" or "if there are more than one jobs"? (excuse my ignorance of C, I'm new to all this) – Chauncey Garrett Apr 17 '12 at 15:38
  • any number of jobs (1, 2, more) – yazu Apr 17 '12 at 15:40
  • 5
    Just for the reference for folks like me who would like to find the docs: both `%(...)` and `%j` can be found in `man zshmisc`, in "expansion of prompt sequences" section (the ternary operation is in "conditional substrings in prompts" subsection). – dvk Jun 12 '18 at 13:27