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

Bash脚本字符串比较报错:[Nothing: command not found问题求助

Bash脚本条件判断错误解决方法

我编写了如下Bash脚本:

vartest=(`/usr/local/pgsql/bin/psql -h 10.0.1.143 -t -p 6432 -d gpperfmon -c "select delete_oldest_db_test();"`)
echo ${vartest[2]}


what_to_delete=${vartest[2]}

if ["$what_to_delete" == "Nothing"]; then
echo "Nothing to delete"
else
dropdb -h 10.0.1.143 -p 6432 -U postgres ${vartest[0]}

fi

运行时出现错误:

line 7: [Nothing: command not found

问题出在条件判断的这一行:

if ["$what_to_delete" == "Nothing"]; then

解决方法

错误核心是[(test命令的简写)和后续表达式之间必须添加空格——Bash会将["$what_to_delete"识别为一个完整的命令,因找不到该命令而报错。

修正方案1:给[和表达式之间加空格

if [ "$what_to_delete" == "Nothing" ]; then

修正方案2:使用Bash原生[[ ]]语法(更推荐)

[[ ]]是Bash的扩展语法,无需担心空格问题,还支持更丰富的字符串匹配逻辑:

if [[ "$what_to_delete" == "Nothing" ]]; then

额外优化建议

  • 命令替换推荐用$()替代反引号,可读性更强且支持嵌套:
    vartest=$(/usr/local/pgsql/bin/psql -h 10.0.1.143 -t -p 6432 -d gpperfmon -c "select delete_oldest_db_test();")
    
  • 数组取值时添加引号,避免字段拆分或空白字符导致的异常:
    echo "${vartest[2]}"
    what_to_delete="${vartest[2]}"
    

内容的提问来源于stack exchange,提问作者Matias

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:40:35