我在实现 for 循环时遇到问题。执行脚本时出现此错误
test1.sh:2:语法错误:循环变量错误
我不明白这个错误。
这是我的脚本
#!/bin/bash
for (( c=1; c<=5; c++ ))
do
echo "Welcome $c times..."
done
谁能告诉我 ubuntu 中 sh 中 for 循环的语法(在 ubuntu 中它链接到 dash shell)shell?
我在实现 for 循环时遇到问题。执行脚本时出现此错误
test1.sh:2:语法错误:循环变量错误
我不明白这个错误。
这是我的脚本
#!/bin/bash
for (( c=1; c<=5; c++ ))
do
echo "Welcome $c times..."
done
谁能告诉我 ubuntu 中 sh 中 for 循环的语法(在 ubuntu 中它链接到 dash shell)shell?
您可能使用 运行它sh
,而不是运行它bash
。尝试bash test1.sh
,或者./test1.sh
如果它是可执行的,但不是sh test1.sh
.
标准 POSIX shell 只接受语法for varname in list
类似 C 的 for 循环语法for (( expr1; expr2; expr3 ))
是一种 bashism。
您可以使用在标准 POSIX shell 中获得类似的行为for c in $(seq 1 5)
您的 shell 脚本(如图所示)在 Korn shell 和 Bash 中运行。一些想法:
syntax error: '(' unexpected
)。for ((x;y;z))
结构。试试这个:
#! /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
在执行时显示所有行。$RANDOM
是 BASH 或 Kornshell,则应该显示一个值(您的 for 循环将在任何一个中工作)。{$BASH_VERINFO[x]}
BASH 时才应设置。即使您在 BASH 中运行 Korn shell,也不会设置这些(不像 $SHELL 仍然包含bash
)。如果 for 循环仍然给您带来麻烦,请删除它。在这个脚本的某个地方,我们会查明您是否真的在执行 bash shell。
做什么
ls -l /bin/sh
给你的机器?
建立sh
一个符号链接bash
然后你可以做sh ./test1.sh