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

Shell Script的if else语句未按预期工作,求排查问题

Shell脚本if else密码判断始终返回正确的问题解决

你的代码核心问题是条件判断的语法错误:

在Shell的[ ](等同于test命令)中,比较操作符=的两边必须保留空格。你写的[ $pass="password" ]会被Shell解析成“检查字符串$passpassword是否非空”——不管你输入什么,这个拼接后的字符串都不会是空的,所以条件永远为真,自然每次都走正确分支。

另外,为了避免输入空值时出现语法错误,建议给变量加上双引号,修正后的代码如下:

#!/bin/bash
clear

echo "Enter password"
read pass
if [ "$pass" = "password" ]
then
  echo "The password is correct."
else
  echo "The password is incorrect, try again."
fi

如果你用Bash的话,更推荐使用[[ ]]进行条件判断,它的语法更宽松,也不需要担心空值和空格的问题,写法如下:

#!/bin/bash
clear

echo "Enter password"
read pass
if [[ $pass == "password" ]]
then
  echo "The password is correct."
else
  echo "The password is incorrect, try again."
fi

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 06:05:21