Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print even numbers from a user supplied input [duplicate]

Tags:

linux

bash

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)) ]'
like image 211
cookiemonster Avatar asked Mar 08 '23 12:03

cookiemonster


2 Answers

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
like image 176
janos Avatar answered Apr 05 '23 22:04

janos


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.

like image 37
agc Avatar answered Apr 05 '23 22:04

agc