4

I have this code here and what its supposed to do it this:

the user enters the Max number. and based on that number entered, I want to display all the even numbers up to that number.

#! /bin/bash
echo "What is your max number:"

read counter


for number in {0.."$counter"}

if [ (($number % 2 == 0)) ]
then
echo "$number"
fi

but it doesn't work. rather I receive this error when I call he script from the terminal:

[root@sunshine Desktop]# bash Tester
What is your max number:
9
Tester: line 9: syntax error near unexpected token `if'
Tester: line 9: `if [ (($number % 2 == 0)) ]'
cookiemonster
  • 368
  • 1
  • 8
  • 22

2 Answers2

5

You forgot the do and done parts of the for loop. And in any case, you cannot use a variable with the {a..b} syntax, unfortunately. You need to write as a counting loop instead. And then you can increment by 2, which eliminates the check for even numbers:

for ((number = 0; number < counter; number += 2)); do
    echo "$number"
done

Lastly, I recommend to rename the variables to:

  • counter -> max
  • number -> counter

Putting it all together:

#!/bin/bash

echo "What is your max number:"    
read max

for ((counter = 0; counter < max; counter += 2)); do
    echo "$counter"
done
janos
  • 120,954
  • 29
  • 226
  • 236
  • 3
    The reason why you can't use {0..$var} is because brace expansion is done before parameter expansion, therefore it is not a valid expansion at the time Bash processes it. You can refer to [manual](https://www.gnu.org/software/bash/manual/bashref.html#Shell-Expansions) for more information. – PesaThe Nov 24 '17 at 22:40
2

Simpler method:

seq 0 2 $counter

Variables can be passed to brace expansion, using another invocation of bash:

bash -c 'printf "%i\n" {0..'$counter'..2}'

Or eval:

eval 'printf "%i\n" {0..'$counter'..2}'

Neither of those last two methods is safe, unless it's certain that $counter is a number.

agc
  • 7,973
  • 2
  • 29
  • 50