41

Here is my code:

#!/bin/bash
if [ "$#" -ne 2 ] ; then
        echo "$0: exactly 2 arguments expected"
        exit 3
fi

if [$1 != "file" -a $1 != 'dir'] ; then
        echo "$0: first argument must be string "file" or "dir""
        exit 1
elif [-e $2 -a -r $2]; then
        if ["$1" = "file" -a -f $2] ; then
                echo YES
        elif ["$1" = "dir" -a -d $2] ; then
                echo YES
        else
                echo NO
        fi
        exit 0
else
        echo "$0: $2 is not a readable entry"
        exit 2
fi

If I run ./lab4 file filename1 it will check if the first parameter is the string "file" or "dir" then if the first parameter is "file" and filename1 is a file, it will print yes. Same thing for dir.

It doesn't recognize $1 and $2. The code will output:

./lab04Q2: line 7: [file: command not found
./lab04Q2: line 10: [-e: command not found

even though I did put 2 parameters when running the program.

2
  • Hi Janson, I've edited your question for you. In future, consider using a 4 space indent on anything that should be treated as code in your posts here. Commented Feb 13, 2012 at 2:51
  • 1
    thanks I thought indent meant using tab, but that didnt work
    – JA3N
    Commented Feb 13, 2012 at 2:58

2 Answers 2

70

Try the following 3 lines in bash:

if [ "a" == "a" ]; then echo hi; fi
if ["a" == "a" ]; then echo hi; fi
if ["a" == "a"]; then echo hi; fi

You'll see that only the first one works, whereas the other two do not. i.e. it's your lack of spaces is the reason why your expression doesn't work.

The above example also suggests that you can test out bash syntax directly on the bash prompt. You can get it right before incorporating them into your script.

1
  • I used your approach and didn't work this does work in case: if [ "a"=="a" ]; then echo hi; fi Without spaces between the values and equal signs Commented Sep 9, 2017 at 16:43
39

The problem(s) come from the fact that [ is actually a command. In fact it's an alias for the test command. In order for this to run properly, you'll need to add a space after your [ as in:

if [ $1 != "file" -a $1 != 'dir' ] ;

Do this for all your instances of [ that don't have a space after it.

P.S.

Since you're using bash as your interpreter, I highly suggest you use [[ ]] instead of [ ] for your tests as the former is a lot more capable than the latter with no downsides; no need for a space is one of them

2
  • like if [[$1 != "file" -a $1 != 'dir' ]] ; ?
    – JA3N
    Commented Feb 13, 2012 at 2:56
  • 4
    @JansonChung [[ ]] allows for more C-like syntax so you can actually do if [[$1 != "file" && $1 != "dir"]]; then ...
    – SiegeX
    Commented Feb 13, 2012 at 3:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.