我是bash脚本的新手。我有一个剧本,我正在为一个学校项目工作,但它没有按预期工作。我在if-then语句中不断收到错误。
#!/bin/bash
echo –e “Would you like to add a new employee’s information? y/n n”
read EMPLOYEE
if [ $EMPLOYEE = “y” –o $EMPLOYEE = “Y” ]
then
echo –e “Please enter employee’s first name c”
read FIRST
echo –e “Please enter employee’s last name c”
read LAST
echo –e “Please enter empolyee’s ID c”
read ID
echo –e “$FIRSTt$LASTt$ID” >> database
fi
echo –e “Would you like to search for an employee? y/n n”
read SEARCH
if [ $SEARCH = “y” –o $SEARCH = “Y” ]
then
echo –e “Enter the first name, last name or employee ID to search for. c”
read WORD
grep “$WORD” database
fi
即使是bash版本3,以下内容也应该按您的预期工作,并且在某种程度上是正确的;-)
#!/bin/bash
printf "Would you like to add a new employee’s information? y/n n"
read -r EMPLOYEE
if [ "$(tr '[:upper:]' '[:lower:]' <<<"$EMPLOYEE")" = "y" ]
then
printf "Please enter employee’s first name : c"
read -r FIRST
printf "Please enter employee’s last name : c"
read -r LAST
printf "Please enter empolyee’s ID : c"
read -r ID
printf "%st%st%s" "$FIRST" "$LAST" "$ID" >> database
fi
printf "Would you like to search for an employee? y/n n"
read -r SEARCH
if [ "$(tr '[:upper:]' '[:lower:]' <<<"$SEARCH")" = "y" ]
then
printf "Enter the first name, last name or employee ID to search for. : c"
read -r WORD
grep "$WORD" database
fi
关于重构/修复的说明:
- 在大多数情况下,不要依赖CCD_
- 使用CCD_ 2在输入上移动反斜杠
- 从输入中引用变量(使用真正的ASCII引用字符),因为shell解析器在其他方面会做一些有趣的事情
- 不针对y和y进行测试,而是简单地将接收到的字符串小写,以仅比较一个变体
- 使用一些缩进概念进行跟踪,以及
- 正如一位评论者已经建议的那样使用shell linter(目前效果很好)
上述代码在上述linter中没有指示错误。
作为读者练习的小任务(感谢andlrc:)
- 使用小写变量名,我会修改有意义的名称享受shell编码的学习吧