当尝试运行以下命令时,我在vi中一直得到以下语法错误"语法错误接近意外的标记' case'":
#!/bin/bash
if [ -z $1 ]
then
NAME="Person"
elif [ -n $1 ]
then
NAME=$1
fi
for NAME
case $NAME in
"Alice") echo "$NAME is a member of the name group.";;
"Bob") echo "$NAME is a member of the name group.";;
"Charlie") echo "$NAME is a member of the name group.";;
"Quan") echo "$NAME is a member of the name group.";;
"Brandon") echo "$NAME is a member of the name group.";;
*) echo "Sorry, That $NAME is not a member of the name group.";;
esac
#!/bin/bash
#Will also work with dash (/bin/sh)
#Shorter default-value assignment
#+ no need for an all-cap variable
name="$1"
: "${name:=Person}"
#`for name` doesn't belong here
case "$name" in
"Alice") echo "$name is a member of the name group.";;
"Bob") echo "$name is a member of the name group.";;
"Charlie") echo "$name is a member of the name group.";;
"Quan") echo "$name is a member of the name group.";;
"Brandon") echo "$name is a member of the name group.";;
*) echo "Sorry, That $name is not a member of the name group.";;
esac
全大写变量通常用于:
- 导出到或从环境 继承的变量配置shell的变量
不需要全大写
在默认情况下引用"$variables"
是一个很好的做法,除非您特别想在空格上分割(或者更准确地说是$IFS
)。
for
循环条件不完整。
请看下面的例子:
for循环与其他编程语言略有不同。基本上,它让你遍历字符串中的一系列'words'。
一个例子:
for i in $( ls ); do
echo item: $i
done
您将需要在脚本中对NAME
进行迭代。
EDIT实际上,正如注释指出的那样,您甚至根本不需要在代码中使用for
循环。你可以把它拿出来。但是如果你需要写一个合适的for,请考虑到这一点。
只是语法错误,试试这个
#!/bin/bash
if [ -z $1 ]
then
NAME="Person"
elif [ -n $1 ]
then
NAME=$1
fi
case $NAME in
"Alice") echo "$NAME is a member of the name group.";;
"Bob") echo "$NAME is a member of the name group.";;
"Charlie") echo "$NAME is a member of the name group.";;
"Quan") echo "$NAME is a member of the name group.";;
"Brandon") echo "$NAME is a member of the name group.";;
*) echo "Sorry, That $NAME is not a member of the name group.";;
esac