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?
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.
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.
Several things to try:
bash myscript.sh instead of simply myscript.sh. This will guarantee you're running under BASH.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.