You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 16:01:09