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
相关产品推荐
相关产品推荐

