Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

324
Views
why is this simple FOR LOOP in my Linux bash not working?

I'm trying to do a simple for loop in a UNIX script (bash).

Here's my script:

for i in {1..3}
do
   echo "Welcome $i times"
done

I was expecting this for output ...

Welcome 1 times
Welcome 2 times
Welcome 3 times

... but I get this ...

Welcome {1..3} times

What am I doing wrong?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You didn't mention how you were executing your script and that can make a difference. Suppose we have a script:

$ cat welcome.sh
for i in {1..3}
do
   echo "Welcome $i times"
done
echo "\n"

Observe the following three invocations of welcome.sh from a bash shell:

$ ps -p $$
  PID TTY          TIME CMD
11509 pts/25   00:00:00 bash
$ source welcome.sh
Welcome 1 times
Welcome 2 times
Welcome 3 times

$ bash welcome.sh
Welcome 1 times
Welcome 2 times
Welcome 3 times

$ sh welcome.sh
Welcome {1..3} times

The last one fails because, on my system, sh defaults to dash, not bash. This is true, for example, for any modern Debian/Ubuntu-derived system.

over 4 years ago · Santiago Trujillo Report

0

Moving my comment to formal answer:

set -o braceexpand

That enables {x..y} style (amongst other kinds of) expansion. If you want it permanently, add it to your .bashrc. If you want it temporarily, you can "bracket" your code:

set -o braceexpand  # enable brace expansion
echo {1..3}         # or whatever your command is
set +o braceexpand  # disable it

Frankly I think the code overhead of that on/off approach isn't worth it, and I always add brace expansion to my .bashrc.

Finally, here's an excellent discussion of brace expansion ins and outs.

over 4 years ago · Santiago Trujillo Report

0

Several things to try:

  • Run your script with bash as a prefix. bash myscript.sh instead of simply myscript.sh. This will guarantee you're running under BASH.
  • Run set -o and see if braceexpansion is set to on. If not, run set -o braceexpand and see if that fixes your problem.

You can test for whether braceexpand is on or off with the -o test.

if [[ -o braceexpand ]]
then
    echo "Brace expand is on"
else
    echo "It is off"
fi

You can use this to test the state of braceexpand, so you can return it to its previous state.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!