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:
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.
$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.
dollar-bang gets the PID of the last backgrounded process.
http://tldp.org/LDP/abs/html/internalvariables.html (Search for '$!')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With