I have the following code in a file that is sourced by both zsh and bash.

if test $SHELLNAME = zsh ; then
    lss() { l -l ${1:-.}/*(s,S,t); }
    laf() { l ${1:-.}/.*(.); }
    lad() { l -d ${1:-.}/.*(/); }
    lsw() { l -ld ${1:-.}/.*(R,W,X.^ND/); }

SHELLNAME is zsh if the shell is zsh and bash if the shell is bash.

Each of the above functions contains code that works with zsh, but not bash.

When I source this file, I receive the following errors.

bash: <filename>: line 67: syntax error near unexpected token `('
bash: <filename>: line 67: `     lss() { l -l ${1:-.}/*(s,S,t); }'

At the moment, I am using eval to bypass bash's syntax checking.

if test $SHELLNAME = zsh ; then
    # Using eval makes sure bash can't try to syntax-check these functions.
    eval 'lss() { l -l ${1:-.}/*(s,S,t); }'
    eval 'laf() { l ${1:-.}/.*(.); }'
    eval 'lad() { l -d ${1:-.}/.*(/); }'
    eval 'lsw() { l -ld ${1:-.}/.*(R,W,X.^ND/); }'

Is there a better solution to this problem? (perhaps one that doesn't use eval)


You only need one eval.

[ -n "$ZSH_VERSION" ] &&
  eval '
    lss() l -l ${1:-.}/*(s,S,t)
    laf() l ${1:-.}/.*(.)
    lad() l -d ${1:-.}/.*(/)
    lsw() l -ld ${1:-.}/.*(R,W,X.^ND/)

(note that zsh contrary to bash does support the Bourne function syntax)


[ -n "$ZSH_VERSION" ] && . /dev/fd/3 3<< '# End of zsh specific section'
  lss() l -l ${1:-.}/*(s,S,t)
  laf() l ${1:-.}/.*(.)
  lad() l -d ${1:-.}/.*(/)
  lsw() l -ld ${1:-.}/.*(R,W,X.^ND/)
# End of zsh specific section

But I'd tend to agree with slm that having the zsh specific syntax in a separate file only sourced by zsh would make sense.

| improve this answer | |
  • Thanks for putting into code what I could only think of in words 8-). – slm May 26 '13 at 15:11

Rather than try and get Bash to not syntax check, why not have your script that's doing the sourcing of this only source it when it's being called by the correct shell.

| improve this answer | |
  • The file is sourced by both bash and zsh. I'm thinking about splitting the zsh-specific parts into their own file though. – user26112 May 26 '13 at 15:12
  • 6
    Yeah that's exactly what I would do. It's clearer to maintain and support for yourself down the road and for anyone else that comes into the code in the future. In code I always try for explicit rather than clever. – slm May 26 '13 at 15:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy