linux - Shell 脚本大小写语法错误

标签 linux bash vi

尝试运行以下命令时,我在 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)。

关于linux - Shell 脚本大小写语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33313737/

相关文章:

linux i2c 模块不完整 xfer (0x48) 错误

node.js - 在 Manjaro linux 上安装 node js 和 npm 的问题

linux - 将数据从程序写入文件

vim 在每行末尾显示空 block

vi - 如何利用 "vi -t"查找系统调用的源码? FreeBSD

linux - 是否可以在没有 GNOME 或类似软件的情况下运行 GTK+ 应用程序?

Bash:根据标志重定向到屏幕或/dev/null

regex - 如何使用 sed 提取复杂的版本号?

linux - 如何修改netcat的输入流?

vim - 如何在 vim 的命令行模式下粘贴文本?