Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a for loop in bash using a variable

Tags:

bash

I want to create a for loop in bash that runs from 1 to a number stored in a variable in bash. I have tried doing what the answer to this question tells, but it produces this error:

Syntax error: Bad for loop variable

My OS is Ubuntu 12.04 and the code looks like this:

#!/bin/bash
TOP=10
for ((i=1; i<=$TOP; i++))
do
    echo $i
done

What does this error message mean? Here is an output image:

enter image description here

like image 301
Krøllebølle Avatar asked Jul 16 '26 01:07

Krøllebølle


1 Answers

C-style for loop works only in few shells and bash is among them. This is syntax is not part of POSIX standard.

#!/bin/bash
TOP=10
for ((i=1; i<=$TOP; i++))
do
    echo $i
done

POSIX-compliant for loop will be the following

#!/bin/bash
TOP=10
for i in $(seq 1 $TOP)
do
    echo $i
done

This works both in bash and sh.

To know which shell you are logged in, execute the following command

ps -p $$

Where $$ is PID of current process and the current process is your shell, and ps -p will print information about this process.

To change your login shell use chsh command.

like image 137
divanov Avatar answered Jul 18 '26 05:07

divanov