【问题标题】:IF statement output in bash?bash中的IF语句输出?
【发布时间】:2017-04-06 10:18:12
【问题描述】:

当我运行这个脚本时,它问的第一个问题是“你想使用 curl 吗?[Y/N]:”我的回答通常是 Y 或 y。但是,当我这样做时,我得到的即时输出是“未知!”。我期待从代码中看到下一个问题“太好了,你想忽略证书 [Y/N]:”

任何人都可以编辑我的代码以使其按预期工作吗?告诉我为什么?

#!/bin/bash

echo "Build command"

read -r -e -p "Would you like to use curl? [Y/N]: "

curlstring="curl"

if [[ "${input,,}" == "y" ]]; then    
    read -r -e -p "Great, do you want to ignore certificates [Y/N]: " input

    if [[ "$input" == "y" ]]; then
        curlstring=$curlstring" -k"
    else
        curlstring=$curlstring" "
    fi

    echo "$curlstring"    
elif [[ "${input,,}" == "n" ]]; then
    echo "Bye"    
else
    echo "Unknown!"
    exit 0
fi

【问题讨论】:

  • 嗨亚伦,我是亚伦。你应该在你的第一个read 命令的末尾添加input,就像你在第二个命令中所做的那样,以便你之后测试的$input 变量对应于用户的输入。
  • 非常感谢 Aaron,这解决了我的问题(编码新手)
  • 不客气,Aaron,很高兴帮助同音词:) 顺便说一句,下次尝试使用bash -x <script> 执行脚本,它会显示程序执行期间发生的情况,您可能会看到读取时没有更改任何变量,并且您正在针对未设置的变量进行测试。
  • 啊,我明白了,我相信这会派上用场。谢谢

标签: bash if-statement output


【解决方案1】:

错误是你的 not 实际上是从第一个 read 命令捕获用户输入,更改它,

read -r -e -p "Would you like to use curl? [Y/N]: " input

另外bash 对所使用的结构非常敏感,第 15 行

fi echo "$curlstring"

当您将Yy 作为选项之一时,可能会引发语法错误

Would you like to use curl? [Y/N]: Y
script.sh: line 15: syntax error near unexpected token `echo'
script.sh: line 15: `    fi echo "$curlstring"    '

将其更改为单独的行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    相关资源
    最近更新 更多