Bash – ‘switch’ based on shell

bashcshshelltcshzsh

I would like to source (i.e. not call) a script from any shell (bash/csh are the primary targets, but fish, zsh, ksh, and rc would also be interesting).

I would like if the script can be a single file – i.e. not a file for each shell dialect.

Can I do that?

I am thinking of something similar to:

  if shell is bash then
    # bash code here
  else
    if shell is csh then
      # csh code here
    else
      if shell is xxxsh then
        # xxxsh code here
      fi
    endif
  fi

So I can do:

csh% source my_script
bash$ . my_script

The trouble is – of course that if is not the same in each dialect, so I somehow need to use syntax that is valid for every shell.

Edit

Detecting the shell is the first step of which determine shell in script during runtime is doing a great job of.

An equally important step is how the code for the different sections for shells should be quoted to not confuse other shells. Think: How can you in the section for bash have a <<here_document containing all characters in all combinations legal in bash but illegal in any other shell without this confusing the other shells. This is not covered by any of the answers/linked answers.

Best Answer

Instead of writing fragments of code for every shell, you should just write portable code, which can be interpreted by most shells. You should look at the POSIX Shell Command Language. This is a standard how a shell (which honors POSIX) should interpret code.

Many shells, like bash, can be configured to behave like a POSIX shell. Every shell has his won features and specific notations. Aviod them completely in portable scripts.