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

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

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


当前回答

请使用以下命令:

ps -p $$ | tail -1 | awk '{print $4}'

其他回答

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

# 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)。

有许多方法可以找到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)

在Mac OS X(和FreeBSD)上:

ps -p $$ -axco command | sed -n '$p' 

如果您只是想检查您正在运行(特定版本的)Bash,最好的方法是使用$BASH_VERSINFO数组变量。作为一个(只读)数组变量,它不能在环境中设置, 因此,您可以确定它来自当前shell(如果有的话)。

但是,由于Bash在作为sh调用时具有不同的行为,因此还需要检查以/ Bash结尾的$ Bash环境变量。

在我写的一个脚本中,使用了带-(不是下划线)的函数名,并依赖于关联数组(在Bash 4中添加),我有以下完整性检查(有有用的用户错误消息):

case `eval 'echo $BASH@${BASH_VERSINFO[0]}' 2>/dev/null` in
    */bash@[456789])
        # Claims bash version 4+, check for func-names and associative arrays
        if ! eval "declare -A _ARRAY && func-name() { :; }" 2>/dev/null; then
            echo >&2 "bash $BASH_VERSION is not supported (not really bash?)"
            exit 1
        fi
        ;;
    */bash@[123])
        echo >&2 "bash $BASH_VERSION is not supported (version 4+ required)"
        exit 1
        ;;
    *)
        echo >&2 "This script requires BASH (version 4+) - not regular sh"
        echo >&2 "Re-run as \"bash $CMD\" for proper operation"
        exit 1
        ;;
esac

在第一种情况下,您可以忽略对特性的功能检查,只假设将来的Bash版本是兼容的。

一种方法是:

ps -p $$ -o exe=

在我看来,这比在另一个答案中使用-o args或-o comm更好(这些可能会使用一些符号链接,例如当/bin/sh指向某个特定的shell,如Dash或Bash)。

上面返回的是可执行文件的路径,但要注意,由于/usr-merge,可能需要检查多个路径(例如/bin/bash和/usr/bin/bash)。

还要注意,上面的文件并不完全与POSIX兼容(POSIX ps没有exe)。