1

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.

2
  • 1
    Does echo "${!}" work any better? If you only have one bg job, or can match the command, you could capture the pid from jobs -l Commented Apr 8, 2020 at 21:38
  • yes sleep 100 & pid=${!}; also appears to work Commented Apr 8, 2020 at 22:23

1 Answer 1

3

The ! is the trigger character for history expansion, enabled in interactive shells by default.

I don't think it would do anything useful in pid=$!; like in your case, or in echo "$!". As you can see from the error message, it tries to use an empty string to search for, as opposed to something like !foo looking for foo. Newer versions of Bash are more sensible in that $! or "!" don't trigger it, but 3.2 is a bit stupid with that.

What seems to work is pid=$! ;, with the space before the semicolon. Or you could just disable history expansion with set +H. (Note that "$!" doesn't work in 3.2.)

2
  • the space before the semicolon does indeed fix it. I had no clue that it was required in this case. I've admittedly never been consistent in my usage of that, some scripts I put the space and others I don't. I guess I just got lucky every time all these years wow Commented Apr 8, 2020 at 22:21
  • 1
    @user5359531, in scripts it shouldn't even come up, since history expansion is disabled in that case. It's only a problem if you type a command like that on an interactive shell's prompt. The behaviour on 3.2 is somewhat painful, so I'm not surprised it's been changed. Though personally, I just turned history expansion off for good, with all the quirks it has, it's more of a nuisance than it's useful. (or maybe I just haven't bothered to learn how to use it.)
    – ilkkachu
    Commented Apr 9, 2020 at 8:20

You must log in to answer this question.

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