Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell: Undefined behavior of `for`

Tags:

bash

shell

sh

I have a script that looks like this :

test.sh

!/bin/bash                                                                  
for i in {0..10}                                                          
  do                                                                         
    echo "Welcome $i times"
  done

If I run it like sh test.sh I get Welcome {0..10} times only once

However if I run it as bash test.sh I get :

Welcome 0 times
Welcome 1 times
 .... and so on

Also if I run the same script on a redhat terminal . I get an error :

root@UPLC-PPM-DEV-01 TEST]# sh test.sh 
'est.sh: line 3: syntax error near unexpected token `do
'est.sh: line 3: `  do

What is wrong here ?

like image 459
Deepankar Bajpeyi Avatar asked Feb 23 '26 00:02

Deepankar Bajpeyi


1 Answers

This has nothing to do with for.

The {0..10} syntax is only supported by bash.

In plain sh you can use

seq 0 10

(if your platform supports it), or

i=`expr $i + 1`

to create a counter and use while.

like image 91
Karoly Horvath Avatar answered Feb 25 '26 22:02

Karoly Horvath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!