繁体   English   中英

使用 sh 运行 bash 脚本

[英]Run bash script with sh

我有 bash 脚本,它需要 bash。

另一个人尝试运行它

sh script_name.sh

它失败了,因为 sh 在他的发行版中是 dash 的符号链接。

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

我有一个使用包装脚本的想法:

#!/bin/sh
bash script_name.sh

目标是在具有符号链接到破折号的系统中通过 sh 使用 bash 运行.sh 脚本。

好吧,通常你使用shebang告诉shell使用正确的解释器:

#!/bin/bash

# your script here

您必须将脚本设置为可执行:

chmod +x my_script.sh

并让用户启动它:

./my_script.sh

这似乎比使用包装器脚本简单。

即使用户使用sh / dash或任何类似解释器,您也可以使用jbr test来使用bash运行脚本:

#!/bin/bash

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

# Your script here

这样它就可以正常使用:

sh ./my_script.sh

# or

bash ./my_script.sh

# or

./my_script.sh

在您的脚本之前,您可以执行以下操作:

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

或者更通用的方法是使用$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