0

I'm having a surprising large amount of trouble finding a guide on this.

what's wrong with this shell script:

if ["$1" == "-t"]
then
        echo "t"
elif ["$1" == "-r"]
then
        echo "r"
fi

It's supposed to be a very simple test. if the argument is -t, do one thing, if it's -r do the other.

4
  • 7
    check it with shellcheck.net for the basic errors. It should be trivial! Hint: [ ] (<strike>statements</strike>) commands need spaces around the brackets. Commented May 6, 2015 at 16:01
  • That's it. Add this as an answer so I can accept it. Commented May 6, 2015 at 16:03
  • 1
    @fedorqui (Yeah, this is a nit, but ...) [] is not a statement. [ is a command. Too many people get confused thinking that [ is part of the shell grammar, and calling it a "statement" reinforces that error. Commented May 6, 2015 at 16:04
  • 1
    Never chain if/else like this: case $1 in; -t) echo t;; -r) echo r;; esac Commented May 6, 2015 at 16:05

1 Answer 1

3

[ is a command (see it with man [ or directly to man test). Thus, you need spaces around them in order to be interpreted properly:

if [ "$1" == "-t" ]
then
        echo "t"
elif [ "$1" == "-r" ]
then
        echo "r"
fi

Or better use POSIX compliant =: if [ "$1" = "-t" ] ....

See interesting comments by Charles Duffy and William Pursell below.

Sign up to request clarification or add additional context in comments.

2 Comments

If we're going to try to be pedantically correct, might be preferable to use the (POSIX-compliant) string comparison operator = rather than the extension ==.
Another nit: [] is also not a command! [ is a command, and ] is the last argument to it. It's probably easier to say [] is a command, though, but...let the reader beware!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.