如何确定我正在使用的当前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)。

其他回答

没有一个答案适用于fish shell(它没有变量$$或$0)。

这适用于我(测试在sh, bash, fish, ksh, csh, true, tcsh,和zsh;openSUSE 13.2):

ps | tail -n 4 | sed -E '2,$d;s/.* (.*)/\1/'

该命令输出类似bash的字符串。这里我只使用ps、tail和sed(没有GNU扩展;尝试添加——posix来检查它)。它们都是标准的POSIX命令。我相信尾巴是可以去掉的,但是我的sed fu还不够强。

在我看来,这个解决方案不是很可移植,因为它不能在OS x上工作:(

你可以试试:

ps | grep `echo $$` | awk '{ print $4 }'

Or:

echo $SHELL

我想到了这个:

sed 's/.*SHELL=//; s/[[:upper:]].*//' /proc/$$/environ

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

我对打印父进程的变体:

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

当AWK可以为您运行不必要的应用程序时,不要运行它。