kelp99
kelp99

Reputation: 69

How do you properly nest for loops inside if/else statements in shell script?

I have the following code in Linux:

#!/bin/sh
echo "Enter a number:"; read n;
if (($# != 0)) 
    for ((i=1; i< $n+1; i++)) 
    do
      echo $i
    done
else 
    for ((i=1; i<21; i++)) 
    do
      echo $i
    done
fi

As you can tell, I am trying to print the values from 1 to n. If no user input is given, I automatically print from 1 to 20. When I run this script, it says I have syntax error near unexpected token else. Can somebody please help, I don't know what I'm missing.

Upvotes: 0

Views: 251

Answers (3)

Easton Bornemeier
Easton Bornemeier

Reputation: 1936

You are missing a then. In addition, as others have mentioned, your implementation is bashism, so note the change to the first line.

#!/bin/bash
echo "Enter a number:"; read n;
if (($# != 0)) 
then
    for ((i=1; i< $n+1; i++)) 
    do
      echo $i
    done
else 
    for ((i=1; i<21; i++)) 
    do
      echo $i
    done
fi

Upvotes: 2

Charles Duffy
Charles Duffy

Reputation: 295363

A version of your code that actually works with all /bin/sh implementations might look like:

#!/bin/sh
echo "Enter a number:"; read n;

if [ "$#" -ne 0 ]; then
  i=0; while [ "$i" -lt $(( n + 1 )) ]; do
    echo "$i"
    i=$((i + 1))
  done
else
  i=0; while [ "$i" -lt 21 ]; do
    echo "$i"
    i=$((i + 1))
  done
fi

Note the then, needed for the if construct to be valid; the change from if (( ... )) to if [ ... ]; and the change to for ((;;;)) to a while loop for counting.

Upvotes: 2

bipll
bipll

Reputation: 11940

You're missing then:

if (($# != 0)) ; then

Upvotes: 0

Related Questions