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)) ]'
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With