Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script: started with $! instead of #! and got mysterious behavior. What happened?

Tags:

bash

I accidentally started a bash script with $! instead of #! and got some very weird behavior. I'm trying to figure out what happened.

If you try this script:

$!/bin/bash
echo Hello world!

you will get the following behavior:

$ chmod +x hello
$ ./hello
[nothing happens, get prompt back]
$ exit
exit
Hello world!
$

So it looks like this happened:

  1. A new bash shell spawned.
  2. Upon exit, the rest of the script executed.

What's up? How is anything at all happening? Without #!, how does the shell know to use bash to interpret the script?

Obviously this is a "satisfy my curiosity" rather than "solve my problem" question. Googling does not yield much, probably because #! and $! in queries don't make the Google-bot happy.

like image 610
andrewtinka Avatar asked Oct 19 '11 02:10

andrewtinka


2 Answers

$something is a parameter ("variable") expansion, but $! in particular returns a value that isn't set in your script, so it expands as a zero length string.

Therefore your script is, you are correct, the equivalent of:

/bin/bash
echo Hello world!

The shebang magic number is an old feature of Unix, but the shell is even older. A text file with the execute bit set that the kernel cannot exec (because it's not actually compiled) is executed by a subshell. That is, the shell deliberately runs another shell and passes the pathname as the parameter. This is how commands written as shell scripts were executed before shebang was invented, and it's still there in the code.

like image 128
DigitalRoss Avatar answered Oct 16 '22 12:10

DigitalRoss


dollar-bang gets the PID of the last backgrounded process.

http://tldp.org/LDP/abs/html/internalvariables.html (Search for '$!')

like image 8
Ritch Melton Avatar answered Oct 16 '22 14:10

Ritch Melton