2

I stumbled across this post where user chepner proposed in his answer the usage of \j (as mentioned in the bash manual) to retrieve the current running count of background jobs. Basically it boils down to

num_jobs="\j"
echo ${num_jobs@P}

Can anyone enlighten me on what is going on here exactly? E.g.

  • why ${\j@P} is not working and
  • what @P is doing exactly?
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Alex.
  • 53
  • 6

2 Answers2

4

Like any parameter expansion, you have to supply the name of a parameter, not an arbitrary string. \j isn't the name of a parameter; it's the text you want to get from a parameter expansion.

After the parameter has been expanded, @P further subjects the result to prompt expansion, so that \j is replaced by the number of jobs.

$ num_jobs="\j"
$ echo "${num_jobs}"
\j
$ echo "${num_jobs@P}"
0
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    Thanks! I searched through the bash manual but could not find @P anywhere. Where is this described? – Alex. Dec 20 '18 at 14:56
  • 1
    In the `man` page, it's at the end of the Parameter Expansion section, headed by `${parameter@operator}`. The various operators are listed without the prefixed `@`, though. Search for "Parameter transformation" instead. – chepner Dec 20 '18 at 14:59
  • [Got it](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion)! Very neat trick this is! – Alex. Dec 20 '18 at 15:04
1

The part before the @ is the name of the parameter you're trying to expand, it can't be a string you want to modify somehow. And @P is a parameter expansion introduced in Bash 4.4 (see manual):

${parameter@operator}

The expansion is either a transformation of the value of parameter or information about parameter itself, depending on the value of operator. Each operator is a single letter:

P

The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string (see Controlling the Prompt).

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116