Bash foreach loop works differently when executed

2019-03-06 13:06发布

The following 'oneliner' does what I need:

$ for i in {1..5}; do echo $i; done
1
2
3
4
5

However, when I place exactly the same code into for-each.sh file and execute it, I get different result. Why?

for-each.sh file:

#!/bin/bash
for i in {1..10}; do echo $i; done

Result after execution:

$ ./for-each.sh
{1..10}

EDIT

Uf. I'm sorry. Now I noticed that I executed the for-each.sh by sh ./for-each.sh command and not by ./for-each.sh. I didn't know the difference between bash, sh, dash, ... After reading stackoverflow.com/a/5725402/915756 I realized that I executed the file by dash which points to /bin/sh by default on my Debian machine.

标签: linux bash shell
1条回答
SAY GOODBYE
2楼-- · 2019-03-06 13:22

If you're confident that it is indeed bash executing your script, you can explicitly turn on brace expansion (expansion of {...} expressions) as follows:

set -B   # same as: set -o braceexpand

Make this your script's first command after your shebang. (Conversely, set +B (set +o braceexpand) would turn brace extension OFF.)

Conceivably, your system is configured to have brace extension turned off by default.

查看更多
登录 后发表回答