【问题标题】:If statement goes else every time - bash如果语句每次都去 else - bash
【发布时间】:2026-01-28 12:55:01
【问题描述】:

我是新手,所以我为我的任何错误道歉,我对我缺乏知识感到抱歉(我只是初学者)。 所以在这里,我正在用 li 在 bash 中编写小脚本,并且我有 if 语句,这里是

#!/bin/bash
something=$(whiptail --inputbox "Enter some text" 10 30 3>&1 1>&2 2>&3)
if [ $something ?? 'you' ];
then
    echo "$something"
else
  echo "nope"
fi

具体来说我想从中得到什么 - 我输入一些单词/句子/任何东西来鞭打,如果它包含你们中的一些字符串然后打印它,但每次它都去其他地方;_;。请帮忙。

EDIT 现在可以了,谢谢,但我需要检查字符串是否包含单词。

if [[ $string =~ .*My.* ]]

好像没用

【问题讨论】:

  • ?? 语法对我来说是新的。
  • 你可以简单地做if whiptail --inputbox....,也可以测试if [ -z $something ], then echo "nope", else ...
  • 我怀疑这可能是家庭作业,但 bash if 语句的谷歌可能会出现有关字符串包含的内容。
  • 重读,我怀疑你是对的,?? 实际上是 “我使用哪个运算符?” 问题。
  • Why doesn't my if statement work properly in Bash? 的可能重复项 - 大约 30 分钟前确实有人问过这个问题。

标签: bash whiptail


【解决方案1】:

我完全不明白,失去希望并搜索我遇到的网络

#!/bin/bash
OPTION=$(whiptail –title “Menu Dialog” –menu “Choose your option” 15 60 4 \ “1” “Grilled ham” \ “2” “Swiss Cheese” \ “3” “Charcoal cooked Chicken thighs” \ “4” “Baked potatos” 3>&1 1>&2 2>&3)
exitstatus=$?
if [ $exitstatus = 0 ];
then echo “Your chosen option:” $OPTION
else echo “You chose Cancel.”
fi

我刚刚粘贴了这个脚本来检查它是如何工作并修改它,它不是我的脚本,它应该可以工作,但它说“你选择了取消。”

【讨论】:

    【解决方案2】:

    您可能正在寻找字符串比较运算符,例如==!=。例如,

    if [ "$something" == "you" ]; then
        echo "$something"
    else
      echo "nope"
    fi
    

    如果$something等于you,则回显$something;否则回显nope

    或者,正如 David C.Rankin 在他的评论中提到的,您可以检查字符串变量以证明字符串是否为空。例如,

    if [ -z "$something"] ;then 
    

    字符串为空

    if [ -n "$something" ]; then
    

    字符串非空

    有关此功能的更多信息,请查看TEST 手册页。

    【讨论】: