Is there a way to force a shell script to run under bash instead of sh?
bash, scripting, shell
Solution
As Richard Pennington says, the right way to do that is to have
#!/bin/bash
as the first line of the script.
But that's not going to help if users invoke it using `sh` explicitly. For example, if I type
sh your-script-name
the `#!` line will be ignored.
You can't really prevent people from doing that, but you can discourage it by adding something like this at the top of the script:
#!/bin/bash
if [ ! "$BASH_VERSION" ] ; then
echo "Please do not use sh to run this script ($0), just execute it directly" 1>&2
exit 1
fi
Or you could do something like:
#!/bin/bash
if [ ! "$BASH_VERSION" ] ; then
exec /bin/bash "$0" "$@"
fi
but that could go very wrong very easily; for example, it's probably not guaranteed that `$0`, which is normally the name of the script, is actually a name you can use to invoke it. I can imagine this going into an infinite loop if you get it wrong or if your system is slightly misconfigured.
I recommend the error message approach.
(Note: I've just edited this answer so the error message includes the name of the script, which could be helpful to users.)
Problem
I've been goggling around trying to find this, but I couldn't find anything off hand. I'm sure the answer is straightforward. I'm writing some shell scripts for various purposes to be run by different people, and some of them may invoke the script with "sh" instead of "bash". The script contains tools that do not operate in the regular shell environment and need bash - is there a way to force the script to be run under bash even though it was invoked with "sh"?