12

I am attempting to iterate through 1-30, say hello #number for each except for number 10. This is what I have which is not working

for i in {1..30}; do if [i != 10]; then echo "hello $i"; fi; done

my output from this is bash [i: command not found -- thirty times

1
  • 4
    Just missing the spaces for [ and ]
    – Jeff Schaller
    Jan 15, 2016 at 23:42

2 Answers 2

19

Your if statement is wrong, it should be if [ $i != 10 ]. Spaces around the [ are mandatory, and your variables should have a $ sign before it if you are reading them.

for i in {1..30}; do if [ $i != 10 ]; then echo "hello $i"; fi; done
1
  • I cannot choose your answer ... the only option I have is to choose the first reply as the accepted answer.
    – Oscalation
    Jan 15, 2016 at 23:54
2

if tests commands. if [ ... ] works because [ is a command (/usr/bin/[ or a builtin (usually the latter)) that expects ] as its last argument (just to make things look pretty). But other than that, it takes parameters, which needs to be passed as usual—as a space separated list.

If you don't want to use [, you can do: if test $i != 10; then and it will behave exactly the same.

Alternatively, there's [[ in bash, which is a proper grammar construct that creates a separate context, which allows you to use things like > or && in it with semantics different from what they would mean in a usual command invocation ([ and test are just command invocations), but you still need spaces around [[ and ]].

Not the answer you're looking for? Browse other questions tagged .