How to get shell to self-detect using zsh or bash

前端 未结 8 826
再見小時候
再見小時候 2020-12-08 09:20

I\'ve a question on how to tell which shell the user is using. Suppose a script that if the user is using zsh, then put PATH to his .zshrc and if using bash sho

相关标签:
8条回答
  • 2020-12-08 09:40

    An alternative, might not work for all shells.

    for x in $(ps -p $$)
    do
      ans=$x
    done
    echo $ans
    
    0 讨论(0)
  • 2020-12-08 09:46

    If the shell is Zsh, the variable $ZSH_VERSION is defined. Likewise for Bash and $BASH_VERSION.

    if [ -n "$ZSH_VERSION" ]; then
       # assume Zsh
    elif [ -n "$BASH_VERSION" ]; then
       # assume Bash
    else
       # assume something else
    fi
    

    However, these variables only tell you which shell is being used to run the above code. So you would have to source this fragment in the user's shell.

    As an alternative, you could use the $SHELL environment variable (which should contain absolute path to the user's preferred shell) and guess the shell from the value of that variable:

    case $SHELL in
    */zsh) 
       # assume Zsh
       ;;
    */bash)
       # assume Bash
       ;;
    *)
       # assume something else
    esac
    

    Of course the above will fail when /bin/sh is a symlink to /bin/bash.

    If you want to rely on $SHELL, it is safer to actually execute some code:

    if [ -n "`$SHELL -c 'echo $ZSH_VERSION'`" ]; then
       # assume Zsh
    elif [ -n "`$SHELL -c 'echo $BASH_VERSION'`" ]; then
       # assume Bash
    else
       # assume something else
    fi
    

    This last suggestion can be run from a script regardless of which shell is used to run the script.

    0 讨论(0)
提交回复
热议问题