Unix下Shell脚本If...Else/Elif报command not found问题求助
Shell脚本多分支If报错排查与修复
你的报错根源是Shell条件判断的语法空格问题:[ 是Shell的内置命令(等价于test),它和后续的变量、运算符之间必须有空格,否则会被Shell解析成一个不存在的命令(比如[1),导致command not found错误。
错误的写法示例
if [$option == 1]
这里[和$option之间没有空格,1和]之间也没有空格,Shell会把[$option当成一个完整的命令名,当$option的值是1时,就变成[1,自然找不到这个命令。
修正后的完整脚本
file="database.txt" echo "Type the desired option Option 1: See textfile Option 2: Edit textfile Option 3: Add line to the textfile " read option if [ $option == 1 ] then cat $file elif [ $option == 2 ] then vim $file elif [ $option == 3 ] then echo "Type your line:" read newline echo $newline >> $file else echo "None of the options were chosen" fi
核心修改点是给每个[后、==前后、]前都加上空格。
额外优化建议
如果是用Bash脚本,更推荐使用[[ ]](Bash扩展语法),它对空格的要求更宽松(当然规范写法还是建议加空格),还能避免一些字符串解析的坑:
if [[ $option == 1 ]]
另外,多分支选项场景用case语句会更简洁易读:
file="database.txt" echo "Type the desired option Option 1: See textfile Option 2: Edit textfile Option 3: Add line to the textfile " read option case $option in 1) cat $file ;; 2) vim $file ;; 3) echo "Type your line:" read newline echo $newline >> $file ;; *) echo "None of the options were chosen" ;; esac
内容的提问来源于stack exchange,提问作者fathawk
相关产品推荐
相关产品推荐

