如何确定我正在使用的当前shell ?

仅仅ps命令的输出就足够了吗?

如何在不同风格的Unix中实现这一点?


当前回答

这不是一个非常干净的解决方案,但它是你想要的。

# MUST BE SOURCED..
getshell() {
    local shell="`ps -p $$ | tail -1 | awk '{print $4}'`"

    shells_array=(
    # It is important that the shells are listed in descending order of their name length.
        pdksh
        bash dash mksh
        zsh ksh
        sh
    )

    local suited=false
    for i in ${shells_array[*]}; do
        if ! [ -z `printf $shell | grep $i` ] && ! $suited; then
            shell=$i
            suited=true
        fi
    done

    echo $shell
}
getshell

现在您可以使用$(getshell)——version。

不过,这只适用于kornshell类shell (ksh)。

其他回答

你可以使用echo $SHELL|sed "s/\/bin\// g"

有许多方法可以找到shell及其对应的版本。下面是一些对我有用的方法。

直截了当的

$> echo $0(给你程序名。在我的例子中,输出是-bash。) $> $SHELL(这将带您进入SHELL,并在提示符中获得SHELL名称和版本。在我的情况下bash3.2$。) $> echo $SHELL(这将给你可执行的路径。在我的情况下/bin/bash。) $> $SHELL——version(这将提供有关许可证类型的SHELL软件的完整信息)

独创性的方法

$> *******(输入一组随机字符,在输出中您将获得shell名称。在我的例子中-bash: chapter2-a-sample-isomorphic-app: command not found)

执行以下操作以了解您的shell是否使用Dash/Bash。

ls –la /bin/sh:

如果结果是/bin/sh -> /bin/bash ==>那么你的shell使用的是Bash。 如果结果是/bin/sh ->/bin/dash ==>那么你的shell使用的是dash。

如果你想从Bash更改为Dash或反之亦然,请使用下面的代码:

将shell更改为Bash

注意:如果上述命令导致错误提示/bin/sh已经存在,请删除/bin/sh后重试。

这不是一个非常干净的解决方案,但它是你想要的。

# MUST BE SOURCED..
getshell() {
    local shell="`ps -p $$ | tail -1 | awk '{print $4}'`"

    shells_array=(
    # It is important that the shells are listed in descending order of their name length.
        pdksh
        bash dash mksh
        zsh ksh
        sh
    )

    local suited=false
    for i in ${shells_array[*]}; do
        if ! [ -z `printf $shell | grep $i` ] && ! $suited; then
            shell=$i
            suited=true
        fi
    done

    echo $shell
}
getshell

现在您可以使用$(getshell)——version。

不过,这只适用于kornshell类shell (ksh)。

如果你只是想确保用户正在使用Bash调用脚本:

if [ -z "$BASH" ]; then echo "Please run this script $0 with bash"; exit; fi

或参考

if [ -z "$BASH" ]; then exec bash $0 ; exit; fi