从.sh文件执行时,bash foreach循环的工作方式有所不同 [英] Bash foreach loop works differently when executed from .sh file
问题描述
以下单人"可以满足我的需求:
The following 'oneliner' does what I need:
$ for i in {1..5}; do echo $i; done
1
2
3
4
5
但是,当我将完全相同的代码放入for-each.sh文件中并执行它时,我得到了不同的结果.为什么?
However, when I place exactly the same code into for-each.sh file and execute it, I get different result. Why?
for-each.sh文件:
for-each.sh file:
#!/bin/bash
for i in {1..10}; do echo $i; done
执行后的结果:
$ ./for-each.sh
{1..10}
编辑
Uf.抱歉.现在我注意到我是通过sh ./for-each.sh命令而不是通过./for-each.sh命令执行for-each.sh的.我不知道bash,sh,破折号和...之间的区别……阅读 stackoverflow.com/a/5725402/915756 a>我意识到我在Debian机器上默认使用短划线来执行文件,该文件指向/bin/sh.
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.
推荐答案
如果您确信它确实是bash
执行脚本,则可以明确打开括号扩展(扩展{...}
表达式),如下所示:
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
在执行完爆炸后,将其作为脚本的第一个命令.
(相反,set +B
(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.
这篇关于从.sh文件执行时,bash foreach循环的工作方式有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!