Search code examples
bashshellconfigshzsh

How can I tell what shell is running my init file?


I have an init file (/etc/profile.d/which2.sh) that aliases the which command whenever any shell starts. In bash or sh that is fine but in zsh I don't want that as which is a built-in that is already aware of aliases and functions. How can I have the script 'know' when it is under zsh and not execute the alias?

$0 does not help.

I have fixed the problem by simply unsetting the alias in zsh-specific ~/.zshrc, but I would like to know another way.


Solution

  • How about

    [ "$(which which)" = /usr/bin/which ] && alias which "whichever"
    

    This doesn't verify the name of the shell; rather it verifies the shell's behaviour. That's an instance of a generally-applicable programming paradigm: test behaviour directly whenever possible. (See, for example, browser detection.)

    In this case, if you just checked the shell's name as a proxy for a behaviour check, you might luck out now, but things could break in the future. The name is actually arbitrary, and new names might easily be introduced. For example, in some distros ksh is a hard-link to zsh; zsh will adapt its behaviour in an attempt to emulate ksh. As another example, I have two different zsh versions, one of which is invoked as zsh5.

    Ideally, the test wouldn't depend on the precise location of the which utility, either.