bash for 循环在命令行中工作,但在脚本中失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7063058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:35:36  来源:igfitidea点击:

bash for loop work in command line, but failed in script

bashfor-loopdebian

提问by leon

When a run a for statement in debian bash command line, it works fine. But when I run it in a sh script or run it with bash command, it's keeping report "error near unexpected token `do'" Where is the difference?

当在 debian bash 命令行中运行 for 语句时,它工作正常。但是,当我在 sh 脚本中运行它或使用 bash 命令运行它时,它一直报告“错误接近意外令牌`do'”,区别在哪里?

[leon@www] ~/tmp $ for i in {1..10}; do echo $i; done
1
2
3
4
5
6
7
8
9
10
[leon@www] ~/tmp $ bash for i in {1..10}; do echo $i; done
-bash: syntax error near unexpected token `do'

BTW, all works fine in centos enviorment.

顺便说一句,在centos环境中一切正常。

回答by dogbane

Use the -coption so that bash reads the commands from the string you pass in. Also, use single quotes around the command.

使用该-c选项,以便 bash 从您传入的字符串中读取命令。此外,在命令周围使用单引号。

bash -c 'for i in {1..10}; do echo $i; done'

回答by atlau

your bash command line ends with the first ;

您的 bash 命令行以第一个结尾;

so it gets executed separately as:

所以它被单独执行为:

bash for i in {1..10};
do echo $i;
done

and man bash says command argument should be a file to load: bash [options] [file]

man bash 说命令参数应该是要加载的文件:bash [options] [file]

回答by Cydonia7

You can wrap all your script inside inverted commas or in a file. Because here, you're doing bash for i in {1..10}then do echo $iand so on. You should use -c option if you don't put it in a file.

您可以将所有脚本包装在引号内或文件中。因为在这里,你在做什么,bash for i in {1..10}然后do echo $i等等。如果你不把它放在一个文件中,你应该使用 -c 选项。