如何检查当前shell并通过脚本将其更改为bash?

时间:2014-05-15 12:07:31

标签: bash shell unix

#!/bin/bash
 if [ ! -f readexportfile ]; then
    echo "readexportfile does not exist"
    exit 0
fi

以上是我脚本的一部分。当前shell是/ bin / csh时,我的脚本失败并出现以下错误:

If:表达式语法 然后:找不到命令

如果我运行bash然后运行我的脚本,它运行正常(如预期的那样)。

所以问题是:如果myscript有任何改变当前shell的方式,然后解释其余的代码。

PS:如果我在我的脚本中保留bash,它会更改当前shell,并且脚本中的其余代码不会被执行。

2 个答案:

答案 0 :(得分:0)

您可以使用SHEBANG(#!)来克服您的问题。 在你的代码中,你已经在使用she-bang,但要确保它是第一位的。

$ cat test.sh
#!/bin/bash
 if [ ! -f readexportfile ]; then
    echo "readexportfile does not exist"
    exit 0
 else
        echo "No File"
fi

$ ./test.sh
readexportfile does not exist

$ echo $SHELL
/bin/tcsh

在上面的代码中,即使我使用CSH代码执行,因为我们在代码中提到了shebang。如果没有shebang,那么它将获取您已经登录的shell的帮助。

在这种情况下,您还可以使用

检查bash解释器的位置
$ which bash
or
$ cat /etc/shells |grep bash

答案 1 :(得分:0)

其他回复是正确的,但是,回答你的问题,这应该可以解决问题:

[[ $(basename $SHELL) = 'bash' ]] || exec /bin/bash

exec builtin使用给定命令替换当前shell(在本例中为/bin/bash)。