0

I am wondering if there is any difference between:

long_running.sh & 
pid=$!

and

(
  long_running.sh
) & 

pid=$!

will the pid be capture consistently in both cases, or will there be some differences here?

ultimately, I want to capture the meaningful exit code with:

wait ${pid} || { echo "damn"; exit 1; };
2
  • not exactly. The first one is the PID of the shell running the long_running.sh script. The second one is the shell that is a subshell of your current shell: The shell running the script will be a child of the subshell. May 1, 2018 at 21:28
  • thanks, I added more info to the question, ultimately I just need to get a meaningful exit code using wait May 1, 2018 at 21:31

1 Answer 1

1

A little testing shows my earlier comment is wrong:

$ cat long_running.sh 
#!/bin/bash
sleep 3
echo "long_running: $$"
pstree -ps $$
status=$((RANDOM % 2))
echo "exiting with status $status"
exit $status

$ ./long_running.sh
long_running: 6599
systemd(1)───gnome-terminal-(4112)───bash(5899)───long_running.sh(6599)───pstree(6601)
exiting with status 1

$ ( ./long_running.sh )
long_running: 6618
systemd(1)───gnome-terminal-(4112)───bash(5899)───long_running.sh(6618)───pstree(6621)
exiting with status 0

There's no "man-in-the-middle" shell, so I suppose bash spawns a subshell and execs the commands.

To capture the exit status, you do the correct thing

$ ( ./long_running.sh ) & pid=$!; wait $pid && echo ok || echo damn
[1] 7439
long_running: 7439
systemd(1)───gnome-terminal-(4112)───bash(5899)───long_running.sh(7439)───pstree(7441)
exiting with status 0
[1]+  Done                    ( ./long_running.sh )
ok

$ ( ./long_running.sh ) & pid=$!; wait $pid && echo ok || echo damn
[1] 7457
long_running: 7457
systemd(1)───gnome-terminal-(4112)───bash(5899)───long_running.sh(7457)───pstree(7461)
exiting with status 1
[1]+  Exit 1                  ( ./long_running.sh )
damn
1
  • upvoted, can you add the conclusion of this using plain English, thanks! May 1, 2018 at 23:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .