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"?
Hold the Ctrl key, click your user account's name in the left pane, and select “Advanced Options.” Click the “Login Shell” dropdown box and select “/bin/bash” to use Bash as your default shell or “/bin/zsh” to use Zsh as your default shell. Click “OK” to save your changes.
To exit from the shell:At the shell prompt, type exit. Ta-da!
To terminate the script in case of an error, we can use the “-e” option. and the script exits on an error, it closes the terminal window.
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.)
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