views:

383

answers:

3

I have the following in a file which is sourced both by .bashrc and .zshrc. The syntax is from the site.

if $SHELL=/bin/zsh                                                               
         then
     # to not java .class when running java 
             myclasslist () { reply=(${$(ls *.class)%.class}) }
             compctl -K myclasslist java
fi

Both Zsh and Bash go upset of it.

How can you make a if -clause in sh?

+4  A: 

You need to wrap your condition in the test operator (as well as quotes to get in the habit):

In shell:

#!/bin/sh
if [ "$SHELL" = "/bin/zsh" ]; then
       # do your thing
fi

In bash:

#!/bin/bash
if [ "$SHELL" == "/bin/zsh" ]; then
    # just do it!
fi
seth
Your answer suggests me that there is no way to source the same file for Bash/Zsh, since we cannot use the same syntax in the if -clause. Is this right?
Masi
@Masi - I haven't explored the shell nuances too much but I think as long as you have the shebang line set (e.g. `#!/bin/sh`), sourcing the file "shouldn't" be a problem. It works for me when I source the first example from within bash w/o a problem.
seth
+2  A: 

You need the test alias [ command:

if [ "$SHELL" = "/bin/zsh" ]
then
    myclasslist () { reply=(${$(ls *.class)%.class}) }
    compctl -K myclasslist java
fi
Jeffrey Hantin
A: 

On the web site you mention, they do not use the test operator ([]) because they say:

For example, cat returns 0 if it runs successfully, and 1 if it encounters an error

The if must be followed by a "boolean statement" and if this statement returns 0, the "then" is actually executed...

In your case, Seth's answer is what you're looking for.

LB