On my remote server with bash 4.2.46, I can do this:
$ sleep 100 & pid=$!; echo "$pid"; wait "$pid"
[3] 7646
7646
However, on my Mac with bash 3.2.57, it does not work:
$ sleep 100 & pid=$!; echo "$pid"; wait "$pid"
-bash: !: event not found
What is going on? Somehow I have been using macOS bash
for years without ever running into this problem before... but I swear I have run plenty of shell programs that do this exact $!
method to grab the process id of a background process and never had it break.
echo "${!}"
work any better? If you only have one bg job, or can match the command, you could capture the pid fromjobs -l
sleep 100 & pid=${!};
also appears to work