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


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.


else





Your missing shellcheck.net which can also help you in the future.
– Walter A
Jul 2 at 21:07





"shell" is not a specified environment. Please tag this with the correct shell. Also, check the description of tags. The other two and not just not helpful, they are downright wrong.
– Ulrich Eckhardt
Jul 2 at 21:08





for (( ... )) is a bashism. /bin/sh implementations are not guaranteed to support it.
– Charles Duffy
Jul 2 at 21:10



for (( ... ))


/bin/sh





It's also pretty rare these days to need /bin/sh. If you're trying to write Bash, use /bin/bash.
– dimo414
Jul 2 at 23:14


/bin/sh


/bin/bash




3 Answers
3



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


/bin/sh


#!/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.


then


if


if (( ... ))


if [ ... ]


for ((;;;))


while



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


then


#!/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





Even then, this code isn't compatible with POSIX sh; for ((i=1; i<21; i++)) is a bashism.
– Charles Duffy
Jul 2 at 21:10



for ((i=1; i<21; i++))





Agreed. This was simply to fix the syntax error in his expected implementation
– Easton Bornemeier
Jul 2 at 21:10






Maybe you should change your shebang to be #!/bin/bash then?
– Will Barnwell
Jul 2 at 22:59


#!/bin/bash



You're missing then:


then


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






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages