Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

syntax of for loop in linux shell scripting

I have a problem implementing a for loop. I get this error when I execute my script

test1.sh: 2: Syntax error: Bad for loop variable

I don't understand this error.

This is my script

#!/bin/bash
for (( c=1; c<=5; c++ ))
do
echo "Welcome $c times..."
done

can any one tell me syntax for for loop in sh(in ubuntu it links to dash shell) shell in ubuntu?

like image 705
mkab Avatar asked Apr 11 '11 20:04

mkab


3 Answers

You probably run it with sh, not bash. Try bash test1.sh, or ./test1.sh if it's executable, but not sh test1.sh.

like image 53
Michael Krelin - hacker Avatar answered Sep 28 '22 20:09

Michael Krelin - hacker


A standard POSIX shell only accepts the syntax for varname in list

The C-like for-loop syntax for (( expr1; expr2; expr3 )) is a bashism.

You can get similar behavior in the standard POSIX shell using for c in $(seq 1 5)

like image 34
Ken Bloom Avatar answered Sep 28 '22 20:09

Ken Bloom


What does

ls -l /bin/sh

give on your machine ?

Make sh a symbolic link to bash and then you can do sh ./test1.sh

like image 45
Ankur Agarwal Avatar answered Sep 28 '22 19:09

Ankur Agarwal