Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I tried using this:

$ if [$a == 1] then { echo 'yes'; } fi;

but I get an error:

-bash: syntax error near unexpected token `}'

What is the correct format? I tried several with no luck.

share|improve this question
    
you write bash not csh –  PersianGulf Sep 30 '13 at 6:43
    

2 Answers 2

up vote 5 down vote accepted

[ is just another character, according to bash; it's not self-delimiting. So you need to put spaces around [ and ]. Although you'd be better off using [[ and ]].

And the command following if (yes, [ is a command) must be terminated with a ; or a newline.

Finally, == (which is not posix, FWIW; posix prefers =) is string equality, not numeric equality.

So you might have meant:

if [[ $a -eq 1 ]]; then echo yes; fi

But you could use arithmetic evaluation instead:

if ((a == 1)); then echo yes; fi

(In arithmetic evalution, equality is ==, and you don't need $ before variable names. I know it's confusing.)

For more information about [: help test. About [[: help [[ (which builds on test). About ((: help let. About bash: man bash

share|improve this answer

[ is a command in Bash, just like any of the other commands such as if, while, etc. You can see this if you double check the man page:

$ man [
NAME
       bash, :, ., [, alias, bg, bind, break, builtin, caller, cd, command, .....

You can also tell it's a real command with this example:

$ type -a [
[ is a shell builtin
[ is /usr/bin/[

The first result is the builtin version of [ that's part of Bash. The second is the version of [ that's included with the GNU coreutils.

On Fedora you can see what RPM it's a part of:

$ rpm -qf /usr/bin/[
coreutils-8.5-7.fc14.x86_64

Given this you need to make sure that there are spaces around any commands so that they get parsed correctly.

Doing this:

$ if [$a == 1] ...

Would be identical to this:

$ lsblah
bash: lsblah: command not found...

The ls command cannot be parsed correctly because it isn't buffered with spaces so that it's parse-able.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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