2013-10-23 265 views
13

我有bash脚本,它需要bash。用sh运行bash脚本

另一人试图用

sh script_name.sh 

运行它,因为SH是符号链接在他的分布冲失败。

$ 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脚本。

+0

如果你只是做'。/ script_name.sh'? – fedorqui

+2

或让其他用户使用'bash script_name.sh'运行? - 封装也会起作用。你的问题是什么? – John3136

+0

你应该显示你的脚本。你想要的是改变脚本,使其严格符合Posix'sh'标准。 –

回答

25

嘛,平时使用shebang告诉壳使用正确的解释器:

#!/bin/bash 

# your script here 

你hav E要设置脚本为可执行:

chmod +x my_script.sh 

并让用户启动它:

./my_script.sh 

看似简单,而不是使用包装脚本。

您可以使用JBR测试使用bash运行脚本,即使用户使用的是sh /破折号或类似的解释是任何sh:

#!/bin/bash 

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

# Your script here 

这样,它正确地或者工作:

sh ./my_script.sh 

# or 

bash ./my_script.sh 

# or 

./my_script.sh 
+0

但这并不妨碍用户执行'sh script.sh'。 – jbr

+0

@jbr:我添加了一些代码。顺便给你+1。 – neuro

+0

@neuro我修改了您的示例以包含传递给脚本的参数。 – devnull

4

在你的脚本之前您还有别的事情,你可以这样做:

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 
+0

我想'如果[! “$ BASH”];'可能是一个更好的方法。 – devnull

+0

不,因为如果bash用于sh兼容性,'$ BASH'可能是'/ bin/sh'。 – jbr

+0

如果'/ usr/bin'中有'bash'可用? – devnull