Run bash script with sh

别等时光非礼了梦想. 提交于 2019-12-02 22:54:31

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!