2

I'm relatively new to the terminal programming. I'm trying to run an IF condition within a FOR loop. (The command is to be run by a cronjob)

for i in {1..5}; do echo $i; if [ $i>3 ]; then echo $i; fi; done

I want it to output as

1
2
3
4
4
5
5

But the real output from that command is

1
1
2
2
3
3
4
4
5
5

Could anyone help me point out the mistake?

Thanks!

  • Oops misread the question, let me edit! – Arronical Apr 29 '16 at 12:35
7

[ brackets are alias for test command and there is no > sign in the regular test command. Use [ $i -gt 3 ]

$ for i in {1..5}; do echo $i; if  [ $i -gt 3 ] ; then echo $i; fi; done
1
2
3
4
4
5
5

You could use bash's arithmetic expansion (()) as well

$ for i in {1..5}; do echo $i; if  (( $i>3 )) ; then echo $i; fi; done
1
2
3
4
4
5
5

You could use expr too, but I guarantee 100% that you will keep on forgetting to \ escape the < and > sings, as well as redirect output to /dev/null:

$> if expr 3 \> 2 > /dev/null ; then echo YES; else echo NO ; fi                           
YES
$> if expr 3 \< 2 > /dev/null ; then echo YES; else echo NO ; fi                           
NO
  • Thank you, It resolves my problem. I can't accept your answer right now since not allowed to accept in a few minutes – aye Apr 29 '16 at 12:39
  • 1
    $1 should be replaced by $i, by the way :) – aye Apr 29 '16 at 12:40
  • @aye Thanks for catching that. It's hard to write complete answers on cell phone while running to work. I'm making edits to my answer right now. Will post soon – Sergiy Kolodyazhnyy Apr 29 '16 at 13:31
  • [ $(($i>3)) -eq "1" ]? O.o Just if (( i > 3 )) without anything extra will do. It's the cleanest of the lot. – muru Apr 29 '16 at 16:25
  • (And [[ 1 > 2 ]] is string comparison. Try [[ 123 > 2 ]]. – muru Apr 29 '16 at 16:33
2

Editing your command to this should work:

for i in {1..5}; do echo $i; if [[ $i -gt 3 ]]; then echo $i; fi; done

As an extra improvement, if this command will only be run in bash, It's worth using [[ instead of [. It does much the same thing but has some nice additional functionality.

  • That's not what op is asking about. Echo only greater than 3 twice – Sergiy Kolodyazhnyy Apr 29 '16 at 12:35
  • Just spotted that! – Arronical Apr 29 '16 at 12:35
  • Could you read again the question, about the output that i want. Thanks! – aye Apr 29 '16 at 12:35
  • @Arronical There is no > for greater than in bash, use [ $i -gt 3 ] – Videonauth Apr 29 '16 at 12:38
  • 1
    @Videonauth I must not answer Ask Ubuntu questions on my lunch break, really not sure where my head is today! – Arronical Apr 29 '16 at 12:44

Your Answer

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

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