Comparing Command-Line Parameter to a String

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

2 Answers

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

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

Your Answer

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

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest