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

Git Bash中CLI确认脚本报错‘[y: command not found’问题排查

Bash脚本条件判断报错:[y: command not found

问题描述

我正在开发一款基础CLI工具,要求在执行可能不可逆的操作前获取用户确认。以下是验证脚本:

#!/bin/bash

echo "Resetting Database. This will delete all current data in the DB."
read -p "Are you sure you wish to proceed? (y/n): " confirm
if ["$confirm" = "y"]; then 
  echo "Awesome!"
fi

使用-x参数运行脚本查看执行过程,输出如下:

+ echo 'Resetting Database. This will delete all current data in the DB.'
Resetting Database. This will delete all current data in the DB.
+ read -p 'Are you sure you wish to proceed? (y/n): ' confirm
Are you sure you wish to proceed? (y/n): y 
+ '[y' = 'y]'
./test-script.sh: line 4: [y: command not found

问题原因

错误出在bash条件判断中[(test命令的简写)的语法规则上:[的前后必须保留空格。

你的代码里,["$confirm" = "y"]没有在[和变量、]和值之间添加空格,bash会把["$confirm"解析成一个完整的命令名(当用户输入y时,就变成了[y),系统找不到这个命令,因此抛出[y: command not found的错误。

解决方法

修正条件判断行,给[和]前后加上空格即可:

if [ "$confirm" = "y" ]; then 

额外优化建议

  • 兼容大小写输入:允许用户输入Y也触发操作,可以扩展判断逻辑:
    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
    
    或者使用bash扩展正则匹配:
    if [[ "$confirm" =~ ^[Yy]$ ]]; then
    
  • 处理输入空格:如果用户输入带前后空格的内容(比如y),可以先修剪空格:
    confirm=$(echo "$confirm" | xargs)
    

内容的提问来源于stack exchange,提问作者gokul-0hno

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:22:41