Run bash script with sh

user1032985 picture user1032985 · Oct 23, 2013 · Viewed 83.6k times · Source

I have bash script and it requires bash.

Another person try to run it with

sh script_name.sh

And it fails because sh is symbolic link to dash in his distribution.

$ ls -la /bin/sh
lrwxrwxrwx 1 root root 4 Aug 25 16:06 /bin/sh -> dash

I have an idea to use wrapper script:

#!/bin/sh
bash script_name.sh

The goal is to run .sh script by sh with bash in system having symbolic link to dash.

Answer

neuro picture neuro · Oct 23, 2013

Well, usually you use the shebang to tell the shell to use the correct interpreter:

#!/bin/bash

# your script here

You have to set the script to be executable:

chmod +x my_script.sh

And let the user start it with:

./my_script.sh

It seems simple than to use a wrapper script.

You can use jbr test to run your script with bash even if the user use sh/dash or any sh like interpreter:

#!/bin/bash

if [ -z "$BASH_VERSION" ]
then
    exec bash "$0" "$@"
fi

# Your script here

This way it correctly works with either :

sh ./my_script.sh

# or

bash ./my_script.sh

# or

./my_script.sh