简体   繁体   English

使用 sh 运行 bash 脚本

[英]Run bash script with sh

I have bash script and it requires bash.我有 bash 脚本,它需要 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.它失败了,因为 sh 在他的发行版中是 dash 的符号链接。

$ 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.目标是在具有符号链接到破折号的系统中通过 sh 使用 bash 运行.sh 脚本。

Well, usually you use the shebang to tell the shell to use the correct interpreter: 好吧,通常你使用shebang告诉shell使用正确的解释器:

#!/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: 即使用户使用sh / dash或任何类似解释器,您也可以使用jbr test来使用bash运行脚本:

#!/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 : 或者更通用的方法是使用$BASH_VERSION

if [ -z "$BASH_VERSION" ]; then
  echo "Please do ./$0"
  exit 1
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM