如何确定我正在使用的当前shell ?
仅仅ps命令的输出就足够了吗?
如何在不同风格的Unix中实现这一点?
如何确定我正在使用的当前shell ?
仅仅ps命令的输出就足够了吗?
如何在不同风格的Unix中实现这一点?
当前回答
在Mac OS X(和FreeBSD)上:
ps -p $$ -axco command | sed -n '$p'
其他回答
如果你只是想确保用户正在使用Bash调用脚本:
if [ -z "$BASH" ]; then echo "Please run this script $0 with bash"; exit; fi
或参考
if [ -z "$BASH" ]; then exec bash $0 ; exit; fi
我尝试过许多不同的方法,对我来说最好的方法是:
ps -p $$
它也可以在Cygwin下工作,并且不能像PID grepping那样产生假阳性。经过一些清理,它只输出一个可执行名称(在Cygwin With path下):
ps -p $$ | tail -1 | awk '{print $NF}'
你可以创建一个函数,这样你就不必记住它:
# Print currently active shell
shell () {
ps -p $$ | tail -1 | awk '{print $NF}'
}
…然后执行shell。
它在Debian和Cygwin下进行了测试。
如果您只是想检查您正在运行(特定版本的)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版本是兼容的。
$SHELL不需要总是显示当前SHELL。它只反映要调用的默认shell。
为了测试上面的测试,假设bash是默认shell,尝试echo $ shell,然后在同一终端,进入其他一些shell(例如KornShell (ksh))并尝试$ shell。在这两种情况下,您将看到结果为bash。
要获得当前shell的名称,使用cat /proc/$$/cmdline。和通过readlink /proc/$$/exe到shell可执行文件的路径。
Try
ps -p $$ -oargs=
or
ps -p $$ -ocomm=