我开始编写一个仅是文件管理器的脚本,并且我正在设置一个函数,要求用户设置他们首选的文本编辑器,并且它总是以错误消息结束:
/home/user/bin/manager: line 12: syntax error near expected token 'fi'
/home/user/bin/manager: line 12: 'fi'
这是代码:
#!bash/bin
#File managing shell
editor() {
read -p "What file editor would you like to use? (Nano) or (Vi)m " answer
export $answer=$(echo "$answer" | tr '[:upper:]' '[:lower:]')
if [ [ "$answer" -eq "nano" && "vi" && "vim" && "emacs" ] ]
then
editor="$answer"
else
echo "This is embarassing, I didn't understand your input..."
editor ()
fi
}
echo -e "" #this area tells the user he commands and etc. it takes forever to type...
sleep 1
editor()
我有什么遗漏的吗?
谢谢
答案1
第二个和第三个
editor ()
应该只是
editor
仅在函数定义时才需要括号。
bash 的解析器抱怨';'
后缺少()
,但这只是问题的一部分。
答案2
- 用作
#!/bin/bash
shebang。 - 不需要
[ [
...] ]
"$answer" -eq "nano" && "vi" && "vim" && "emacs"
不会测试这四个词的答案。
函数定义
while read -p "What file editor would you like to use? (Nano) or (Vi)m " answer
do
answer=$(echo "$answer" | tr '[:upper:]' '[:lower:]')
case $answer in
( nano | vi | vim | emacs )
$answer ;
## OR
export EDITOR=$answer
break
;;
( * )
echo "This is embarassing, I didn't understand your input..."
;;
esac
done
- 这将检查答案是否是四个有效编辑器之一。
- 值在编辑器中返回
export $answer=
可能会失败(第一次)或给出意想不到的结果(下次)- 用于
$answer
调用编辑器(或$answer "$myfile"
), - 用于
export EDITOR=$answer
设置它, - 或者更好
export EDITOR=$(which $answer)
。