This is an extension to Which shell interpreter runs a script with no shebang?
I was testing my understanding of what interpreter is used, and found some odd behaviour when running a script without a hashbang but as sudo.
Script is as follows:
echo "I am running shell $SHELL"
foo=$'dollar'
echo "run with sudo to see the magic dollar sign <$foo>"
When I ran this script as my normal user, all fine, outputs:
I am running shell /bin/bash
run with sudo to see the magic dollar sign <dollar>
But when I run with sudo I get output
I am running shell /bin/bash
run with sudo to see the magic dollar sign <$dollar>
So without sudo, foo expands to "dollar", but with sudo, the $'' evaluation is ignored and it becomes "$dollar"
I also now understand that $'' not POSIX compliant, and so wouldn't necessarily work if running the script except under bash. And confirm that sudo bash myscript.sh
returns the expect "dollar" output.
However, in any of these scenarious, $SHELL implies the script is running under bash. What is going on?
PS – my /bin/sh links to dash – I can only think it has something to do with this
Best Answer
$SHELL
does not tell you which shell you're running, it tells you what the environment variableSHELL
is. Bash sets this to the path to your login shell iff it's not set already.You are running
sh
(dash
, for you) under sudo, which you can see straightforwardly by usingpstree
:Using
sh
is in line with POSIX, although that part of the specification isn't binding on sudo's implementation choices.readlink /proc/$$/exe
will also confirm that it'sdash
specifically. You could also use any of the other ways of identifying the running shell from the question you linked.In dash,
$'abc'
is a lone dollar sign with no meaning followed by a single-quoted string - basically the same way thatfoo=$
would keep the sign around in any shell.