如何确定我正在使用的当前shell ?
仅仅ps命令的输出就足够了吗?
如何在不同风格的Unix中实现这一点?
如何确定我正在使用的当前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)。
其他回答
在Mac OS X(和FreeBSD)上:
ps -p $$ -axco command | sed -n '$p'
不需要从"ps"的输出中Grepping PID,因为你可以从/proc目录结构中读取任何PID的相应命令行:
echo $(cat /proc/$$/cmdline)
然而,这可能并不比简单地:
echo $0
关于运行一个与名称不同的shell,一个想法是使用之前获得的名称从shell请求版本:
<some_shell> --version
sh似乎失败的退出码2,而其他人给出一些有用的(但我无法验证所有,因为我没有他们):
$ sh --version
sh: 0: Illegal option --
echo $?
2
我想到了这个:
sed 's/.*SHELL=//; s/[[:upper:]].*//' /proc/$$/environ
echo $$ # Gives the Parent Process ID
ps -ef | grep $$ | awk '{print $8}' # Use the PID to see what the process is.
你如何知道你当前的shell是什么?
没有一个答案适用于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上工作:(