0

I was trying a sample program, to check the odd and even no's and was getting an error as below,

#!/bin/bash
N=10

for i in 1..N
if [$i/2 == 0]
then
        echo "even"
else
        echo "Odd"
fi

Error:

./case.sh: line 5: syntax error near unexpected token `if'
./case.sh: line 5: `if [$i/2 == 0]'

EDITED :

#!/bin/bash
N=10

for i in 1..N
do
if(( ($i/2) == 0 ));
then
        echo "even"
else
        echo "Odd"
fi
done

error :

./case.sh: line 6: ((: (1..N/2) == 0 : syntax error: invalid arithmetic operator (error token is "..N/2) == 0 ")
Odd

Correct working code :

#!/bin/bash
N=3

for (( i=1; i <= N; i++ ));
#for i in 1..N; // This didnt work
do
if [[ $i/2 -eq 0 ]]
#if (( i/2 == 0 ));     // This also worked
then
        echo "even"
else
        echo "Odd"
fi
done

2 Answers 2

1

[ ] or [[ ]] needs spaces between its arguments. And in your case you should use [[ ]] or (( )) as [ ] can't handle division along with comparison:

if [[ 'i / 2' -eq 0 ]]; then
if (( (i / 2) == 0 )); then

for i in 1..N; do should also be

for (( i = 1; i <= N; ++i )); do

You probably meant to have a form of brace expansion, but you can't apply a parameter name on it:

{1..10}  ## This will work.
{1..N}   ## This will not work.

Using eval may fix it but better go for the other form of for loop instead.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks konsolebox. bwn why do we use two braces for "for loop" and the if statement
Is it that if there are more than one operation we use an extra brackets
@Angus To make it less complicated, just use if (( (i / 2) == 0 )); then as you're mainly on arithmetic anyway.
Is it that if there are more than one operation we use an extra brackets -> What command do you refer? And can you rephrase this? bwn why do we use two braces for "for loop" and the if statement
You can use single bracket [] when you are doing multiple operations so something like if [ 1 -eq 1 -o 2 -ne 3 ] can written as if [[ 1 == 1 || 2 != 3 ]] when using double bracket. Its just that the [[]] supports ||, && etc. for ease of use and some more additional functionality.
|
1

Try this :

#!/bin/bash
N=10

for i in $(seq 1 $N); do
if [ `expr $i % 2` -eq 0 ]
then
        echo "even"
else
        echo "Odd"
fi
done

1..N is not a valid syntax in bash(though I think you might be coming from ruby background), you can use seq.

2 Comments

does not work here either. shouldn't return 5 odds and 5 evens?
sorry my bad, fixed it now. @KarolyHorvath was correct.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.