Run bash script with sh

2019-03-15 07:15发布

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.

2条回答
甜甜的少女心
2楼-- · 2019-03-15 07:36

In your script before you anything else, you can do something like:

if [ "$BASH" != "/bin/bash" ]; then
  echo "Please do ./$0"
  exit 1
fi

or the more general way is using $BASH_VERSION:

if [ -z "$BASH_VERSION" ]; then
  echo "Please do ./$0"
  exit 1
fi
查看更多
劳资没心,怎么记你
3楼-- · 2019-03-15 07:51

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
查看更多
登录 后发表回答