0

When I start a command in the background via command &, the process ID of the command can be retrieved from the variable $!. This value can be saved and used in later commands, such as kill.

However, a few built-ins, notably fg require a "jobspec", which is a special shell thing that starts with %. So if I start a background command, I can foreground it afterward via command & fg %+, because %+ is the jobspec of the most recently backgrounded command.

If I start two commands in the background, I can foreground the first one using %-, which is the jobspec that is the previous value of %+: command1 & command2 & fg %-.

But this cannot be generalized to three commands. What is needed in general is to be able to save a %nnn jobspec for the command that was just stared in the background. This can be done by something like jobs | sed -e '$!d' -e 's/^\[\([0-9]\+].*$/%\1/, but there ought to be a better way than that.

user2864482
  • 221
  • 1
  • 4
  • Given that job control like `fg` is by default turned off in scripts, it might be that you won't find a simpler answer than just running `jobs` and picking the one you want manually – Eric Renouf May 13 '18 at 01:37
  • Did you know you can use `%string?` as a jobspec? Where "string" is a unique string in the command, followed by a `?`. See `man bash` – cdarke May 13 '18 at 06:55

0 Answers0