Linux shell 脚本中 for 循环的语法
我在实现 for 循环时遇到问题。当我执行脚本时出现此错误
test1.sh:2:语法错误:循环变量错误
我不明白这个错误。
这是我的脚本
#!/bin/bash
for (( c=1; c<=5; c++ ))
do
echo "Welcome $c times..."
done
,谁能告诉我 ubuntu 中 sh(在 ubuntu 中它链接到 dash shell)shell 中 for 循环的语法吗?
I have a problem implementing a for loop. I get this error when I execute my script
test1.sh: 2: Syntax error: Bad for loop variable
I don't understand this error.
This is my script
#!/bin/bash
for (( c=1; c<=5; c++ ))
do
echo "Welcome $c times..."
done
can any one tell me syntax for for loop in sh(in ubuntu it links to dash shell) shell in ubuntu?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能使用
sh
运行它,而不是bash
。尝试bash test1.sh
,或者./test1.sh
(如果它是可执行的),但不是sh test1.sh
。You probably run it with
sh
, notbash
. Trybash test1.sh
, or./test1.sh
if it's executable, but notsh test1.sh
.标准 POSIX shell 只接受语法
for varname in list
类似 C 的 for 循环语法
for (( expr1; expr2; expr3 ))
是一种 bashism。您可以在标准 POSIX shell 中使用
for c in $(seq 1 5)
获得类似的行为A standard POSIX shell only accepts the syntax
for varname in list
The C-like for-loop syntax
for (( expr1; expr2; expr3 ))
is a bashism.You can get similar behavior in the standard POSIX shell using
for c in $(seq 1 5)
你的机器上有什么作用
?
将
sh
设为bash
的符号链接,然后就可以执行sh ./test1.sh
What does
give on your machine ?
Make
sh
a symbolic link tobash
and then you can dosh ./test1.sh
您的 shell 脚本(如图所示)在 Korn shell 和 Bash 中运行。一些想法:
语法错误:'('意外
)。:
> 如果是 BASH 或 Kornshell,则应显示一个值(您的 for 循环将在其中之一中工作)。
{$BASH_VERINFO[x]}
。即使您在 BASH 中运行 Korn shell 也无需设置(与仍包含bash
的 $SHELL 不同),如果 for 循环仍然给您带来麻烦,只需将其删除即可。脚本,我们将了解您是否真的在执行 bash shell。
Your shell script (as shown) runs in both Korn shell and Bash. Some thoughts:
syntax error: '(' unexpected
instead).for ((x;y;z))
construct.Try this:
set -xv
will display all lines as they are executed.$RANDOM
should display a value if this is either BASH or Kornshell (your for loop will work in either one).{$BASH_VERINFO[x]}
should only be set if this is truly BASH. These aren't even set even if you run Korn shell after you're in BASH (unlike $SHELL which will still containbash
).If the for loop still gives you trouble, just delete it. Somewhere in this script, we'll find out if you're really executing a bash shell or not.