Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to force a shell script to run under bash instead of sh? [closed]

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"?

like image 311
Locane Avatar asked Jul 19 '13 17:07

Locane


People also ask

How do I switch from sh to bash?

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.

How do I get out of sh mode?

To exit from the shell:At the shell prompt, type exit. Ta-da!

How do I stop a bash script from closing?

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.


1 Answers

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.)

like image 144
Keith Thompson Avatar answered Oct 18 '22 19:10

Keith Thompson