[英]syntax of for loop in linux shell scripting
I have a problem implementing a for loop. 我在实现for循环时遇到问题。 I get this error when I execute my script 执行脚本时出现此错误
test1.sh: 2: Syntax error: Bad for loop variable test1.sh:2:语法错误:循环变量错误
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? 谁能告诉我ubuntu中sh(在ubuntu中它链接到破折号外壳)shell中for循环的语法?
You probably run it with sh
, not bash
. 您可能使用sh
而不是bash
运行它。 Try bash test1.sh
, or ./test1.sh
if it's executable, but not sh test1.sh
. 尝试bash test1.sh
或./test1.sh
如果它是可执行文件),而不是sh test1.sh
。
A standard POSIX shell only accepts the syntax for varname in list
标准POSIX Shell仅接受for varname in list
的语法
The C-like for-loop syntax for (( expr1; expr2; expr3 ))
is a bashism. for (( expr1; expr2; expr3 ))
的类似于C的for循环语法是一种bashism。
You can get similar behavior in the standard POSIX shell using for c in $(seq 1 5)
您可以for c in $(seq 1 5)
使用标准POSIX shell获得类似的行为。
Your shell script (as shown) runs in both Korn shell and Bash. 您的shell脚本(如图所示)可以在Korn shell和Bash中运行。 Some thoughts: 一些想法:
syntax error: '(' unexpected
instead). 此外,这不是您使用Bourne Shell所得到的syntax error: '(' unexpected
(您会得到syntax error: '(' unexpected
)。 for ((x;y;z))
construct. 但是,即使最旧的Bash版本也可以识别for ((x;y;z))
构造。 Try this: 尝试这个:
#! /bin/bash
set -vx
echo "Random = $RANDOM" #Test for bash/Kornshell. Will be blank in other shells
echo \$BASH_VERSINFO[0] = ${BASH_VERSINFO[0]} #Should only work in BASH
echo \$BASH_VERSINFO[1] = ${BASH_VERSINFO[1]}
echo \$BASH_VERSINFO[2] = ${BASH_VERSINFO[2]}
echo \$BASH_VERSINFO[3] = ${BASH_VERSINFO[3]}
echo \$BASH_VERSINFO[4] = ${BASH_VERSINFO[4]}
echo \$BASH_VERSINFO[5] = ${BASH_VERSINFO[5]}
for ((c=0, c<=5, c++))
do
echo "Welcome $c times"
done
set -xv
will display all lines as they are executed. set -xv
将在执行时显示所有行。 $RANDOM
should display a value if this is either BASH or Kornshell (your for loop will work in either one). 如果它是BASH或Kornshell,则$RANDOM
应该显示一个值(您的for循环可在任何一个中使用)。 {$BASH_VERINFO[x]}
should only be set if this is truly BASH. {$BASH_VERINFO[x]}
仅在确实是BASH的情况下设置。 These aren't even set even if you run Korn shell after you're in BASH (unlike $SHELL which will still contain bash
). 即使您在使用BASH之后运行Korn shell,这些甚至都没有设置(与$ SHELL仍然包含bash
)。 If the for loop still gives you trouble, just delete it. 如果for循环仍然给您带来麻烦,请将其删除。 Somewhere in this script, we'll find out if you're really executing a bash shell or not. 在此脚本中的某个地方,我们将找出您是否真的在执行bash shell。
What does 是什么
ls -l /bin/sh
give on your machine ? 给你的机器?
Make sh
a symbolic link to bash
and then you can do sh ./test1.sh
将sh
设为bash
的符号链接,然后可以执行sh ./test1.sh
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.