【问题标题】:(Shell Script) if else statrement not work as intended?(Shell 脚本)if else 语句没有按预期工作?
【发布时间】:2022-11-20 02:40:27
【问题描述】:

所以我试图学习 Shell Script if else 语句。从互联网上复制此代码,似乎...无法正常工作????????不太确定这里出了什么问题

#!/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

预期输出应为:密码不正确

相反,我得到:密码正确

【问题讨论】:

  • [ $pass="password" ]替换为[ "$pass" = password ]
  • 如果这是确切地什么code from the internet从语法的角度来看,它看起来是错误的;在对代码进行故障排除时,请考虑将您的代码(连同 shebang)剪切粘贴到 shellcheck.net 并进行建议的更改;在这种情况下,shellcheck 将告诉您需要在 = 的每一侧留一个空格

标签: bash shell


【解决方案1】:

你应该有空格:

if [ "$pass" = "password" ]

否则,它将只是评估一个非空字符串,最终评估为“真”。

read pass
echo $pass="password"
> Enter password
test
test=password

【讨论】:

    猜你喜欢
    • 2020-11-28
    • 2020-07-26
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    相关资源
    最近更新 更多