Wednesday, July 27, 2022

[SOLVED] bash for loop: a range of numbers

Issue

I have the following code in an .sh file:

for num in {1..10}
do
  echo $num
done

Which should print numbers from 1 to 10. But, this is what I get:

{1..10}

Also, using C-like sytax doesn't work either:

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

This gets me an error:

Syntax error: Bad for loop variable

The version of bash that I have is 4.2.25.


Solution

The code should be as follows (note the shebang says bash, not sh):

#!/bin/bash
echo "Bash version ${BASH_VERSION}..."
for i in {0..10..1}; do
    echo "Welcome $i times"
done

source http://www.cyberciti.biz/faq/bash-for-loop/



Answered By - Pradheep
Answer Checked By - Cary Denson (WPSolving Admin)