2

I'd like to know if a given script is running under Ash, Dash, Bash, ZSH or something else.

The script may or may not have a shebang line, and it can be executed either directly (my-script.sh) or as an argument to a shell interpreter (sh my-script.sh).

What's the most straightforward way to find that out?

Edit: After reading the answers below and the duplicate question, I've found this to be the most simple and reliable way to find the name of the shell executing a script under Linux:

show_shell() { basename "$(readlink -f /proc/$$/exe)" ;}
Elifarley
  • 1,310
  • 3
  • 16
  • 23

1 Answers1

1

There is no universal, standard way of getting the name that the current shell identifies as.

Prouder shells leave markers you can check:

[ "$BASH_VERSION" ] && echo bash
[ "$ZSH_VERSION" ] && echo zsh
[ "$KSH_VERSION" ] && echo ksh

More humble shells like ash and dash, do not.

This may not be a problem if this point is to run shell specific code, since ash and dash don't include a lot of features outside POSIX anyways.


If (and only if) you are on Linux, you might be able to glean some insights from /proc/$$/exe:

$ dash -c 'ls -l /proc/$$/exe'
lrwxrwxrwx 1 me me 0 Jun 13 11:46 /proc/10933/exe -> /bin/dash

However, for sh it will just say /bin/sh, regardless of which shell actually implements it, though /bin/sh may or may not be a symlink or hardlink to a more identifiable binary.

that other guy
  • 116,971
  • 11
  • 170
  • 194
  • 1
    Your example regarding the use of `$$` works for Dash, but for Bash and ZSH, the path to the inner command (`ls`) is printed: `bash -c 'ls -l /proc/$$/exe'` `/proc/3576/exe -> /bin/ls` – Elifarley Jun 13 '16 at 19:38
  • @Elifarley Good point. This is due to bash/zsh being clever when there's only a single command to be executed. If you use this as part of a script (or add a dummy `; true`), it will show up correctly. – that other guy Jun 13 '16 at 19:42
  • 1
    So I'd declare a function like this: `show_shell() { readlink -f /proc/$$/exe ;}` – Elifarley Jun 13 '16 at 19:43
  • Aside: an important other one to check for is fish, which is "proud" in this taxonomy. ```shell [ "$FISH_VERSION" ] && echo fish` ``` – dan mackinlay Nov 21 '19 at 08:41