How to determine the current shell I'm working on?

How can I determine the current shell I am working on?

Would the output of the ps command alone be sufficient?

How can this be done in different flavors of UNIX?


  • There are 3 approaches to finding the name of the current shell's executable:

    Please note that all 3 approaches can be fooled if the executable of the shell is /bin/sh but it's really a renamed bash , for example (which frequently happens).

    Thus your second question of whether ps output will do is answered with " not always ".

  • echo $0 - will print the program name... which in the case of shell is the actual shell

  • ps -ef | grep $$ | grep -v grep ps -ef | grep $$ | grep -v grep - This will look for the current process ID in the list of running processes. Since the current process is shell, it will be included.

    This is not 100% reliable, as you might have OTHER processes whose ps listing includes the same number as shell's process ID, especially if that ID is a small # (eg if shell's PID is "5", you may find processes called "java5" or "perl5" in the same grep output!). This is the second problem with the "ps" approach, on top of not being able to rely on the shell name.

  • echo $SHELL - The path to the current shell is stored as the SHELL variable for any shell. The caveat for this one is that if you launch a shell explicitly as a subprocess (eg it's not your login shell), you will get your login shell's value instead. If that's a possibility, use the ps or $0 approach.


  • If, however, the executable doesn't match your actual shell (eg /bin/sh is actually bash or ksh), you need heuristics. Here are some environmental variables specific to various shells:

  • $version is set on tcsh

  • $BASH is set on bash

  • $shell (lowercase) is set to actual shell name in csh or tcsh

  • $ZSH_NAME is set on zsh

  • ksh has $PS3 and $PS4 set, whereas normal Bourne shell ( sh ) only has $PS1 and $PS2 set. This generally seems like the hardest to distinguish - the ONLY difference in entire set of envionmental variables between sh and ksh we have installed on Solaris boxen is $ERRNO , $FCEDIT , $LINENO , $PPID , $PS3 , $PS4 , $RANDOM , $SECONDS , $TMOUT .


  • ps -p $$

    应该在涉及ps -efgrep的解决方案(在支持ps POSIX选项的任何Unix变体上)的任何地方工作,并且不会受到通过对可能在其他地方出现的数字序列进行grepping引入的误报的影响。


    Try

    ps -p $$ -oargs=
    

    or

    ps -p $$ -ocomm=
    
    链接地址: http://www.djcxy.com/p/97102.html

    上一篇: exec脚本在shell脚本中有什么用处?

    下一篇: 如何确定我正在使用的当前shell?