2

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

Community
  • 1
  • 1
Krøllebølle
  • 2,878
  • 6
  • 54
  • 79

3 Answers3

10

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.

divanov
  • 6,173
  • 3
  • 32
  • 51
6

You are running the script with sh, not bash. Try:

bash split_history_file_test.sh
Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
0

This code doesn't produce that error. The bash version shipped with that ubuntu version should execute it without problems.

Note: you want to echo $i.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176