0

I want to write a bash script and one of the command line arguments is a string like A:

sh bash.sh file.in A

The script contains:

format=$2

if [$format = "A"]; then 
    ...
else 
    ...
fi

As a result I get this error:

bash.sh: line 20: [A: command not found
Saucier
  • 3,632
  • 1
  • 20
  • 40
EpiMan
  • 809
  • 2
  • 10
  • 24

2 Answers2

3

Try this:

#!/bin/bash

format="$2"

if [ "$format" = "A" ];then
   echo "Equal";
else
   echo "Not equal";
fi

(OR)

if [[ $format = "A" ]];then
    ...
else
    ...
fi
sat
  • 13,503
  • 5
  • 41
  • 62
3

POSIX shell syntax requires a space between the [ ] brackets and the expression.

Try this:

if [ "$format" = "A" ]; then

...

else

...

fi

Also, if portability isn't a concern, you can use the more robust

[[ "$format" == "A" ]]

Additional info: Is [[ ]] preferable over [ ] in bash scripts?

awiseman
  • 4,789
  • 1
  • 16
  • 15
  • 2
    `=` is not an assignment operator in a `test`/`[` command. `==` is only accepted by `bash`, and is arguably a bug to do so. – chepner Mar 17 '14 at 12:42
  • Thanks for the correction. I've edited the incorrect part out. Not sure I like the ambiguity of having an operator mean different things in different contexts... but I'll read up some more on it. – awiseman Mar 17 '14 at 12:47
  • 1
    Since the question is tagged as `bash` shouldn't the expression be `[[ "$format" == "A" ]]`? See https://stackoverflow.com/questions/669452/is-preferable-over-in-bash-scripts – Saucier Mar 17 '14 at 12:49
  • There, how's that for a compromise? :) I've been trying to not presume too much when giving answers and I try to default to as close to the as-posted question as will work. This at least proposes an alternate option. – awiseman Mar 17 '14 at 13:10
  • 1
    It's not just bash that requires the space, it's the POSIX shell syntax that requires a space between any command and its arguments. Don't forget that `[` is a (possibly builtin) command. – glenn jackman Mar 17 '14 at 14:40
  • Hopefully, you guys are getting rep for this. This answer has become a team effort :) – awiseman Mar 17 '14 at 14:45