24

I have an if statement I need to run, as long as the value I have stored in my $counter variable is greater than 5.

Here is the respective section of my current (non-functioning) script:

if $counter > 5
then
    echo "something"
fi

The mistake I'm making is probably very obvious, but for some reason I couldn't find the solution online.. Thanks!

1
  • It's unclear whether this question originally meant to ask specifically for a bash-specific solution or a bash tag was just added to it so the suggested duplicate bash-specific question isn't exactly correct. Close with a POSIX/sh-specific duplicate question if wanted. Commented May 15 at 2:40

2 Answers 2

51

Well that is quite simple:

if [ "$counter" -gt 5 ]
then
    echo "something"
fi
Sign up to request clarification or add additional context in comments.

10 Comments

Unless you need sh compatibility, it's better to use [[ and ]] instead of [ and ]. See mywiki.wooledge.org/BashFAQ/031
Of course. It's meant for compatibility seeing that he didn't mention bash in the title.
@konsolebox, you need to look at the tags below the question. Titles are very often misleading.
If you're using bash, (( counter > 5 )) is even better.
does that work inside double brackets? eg [[ (( counter > 5 )) ]] ?
No, double parentheses are a command just like double brackets; use them instead of brackets. Inside double brackets, the parentheses are just used for grouping.
@glennjackman I'm actually not sure if everyone who tags bash knows the difference between bash and simply sh. (Commenting for reference).
|
27

Arithmetic needs to be done between (( and )):

if (( $counter > 5 ))

Incidentally, you can also leave off the $ in arithmetic, though it doesn't hurt to keep it.

4 Comments

Yes however, I would argue conditional expressions should be done in [[ ]]. So which one should really be it? I'd pick [[ ]]. See my arguments here: stackoverflow.com/a/18568726/445221. (Commenting for reference).
$counter and counter aren't completely identical. If you want counter='' to be identical to counter=0, take the $ off; if you want it to be an error, put it on.
would if [[ $counter -lt 5 ]]; then ... also work?
You mean -gt, but then yes. See also the accepted answer.

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.