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

2
  • works fine with GNU bash, version 4.1.10(4)-release (i686-pc-cygwin) Commented Oct 26, 2012 at 10:36
  • My version is GNU bash, version 4.2.24(1)-release (x86_64-pc-linux-gnu) Commented Oct 26, 2012 at 10:45

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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

bash split_history_file_test.sh

2 Comments

Jeez, didn't know that, thanks. Doesn't sh run a bash script?
@Krøllebølle The Bourne shell (sh) has a different syntax for for loops. The Bash command syntax is a superset of the Bourne shell command syntax.
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.

4 Comments

The echo $1 was just a typo, fixed now. My script still produces the above error, even though it is seemingly not supposed to.
copy-paste your script. how do you execute it?
I have copy-pasted in exactly my script now. The script is run by doing "sh file.sh" in the bash and I have first done "chmod +x file.sh".
I put in an image showing how i run the file. Ubuntu is run as a virtual machine using VMWare Player (shouldn't matter).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.