【问题标题】:Why is my If Statement in Bash not working?为什么我在 Bash 中的 If 语句不起作用?
【发布时间】:2016-03-18 16:29:22
【问题描述】:

您好,我正在 bash 中创建一个归档系统,其中包含一个冗长且凌乱的 if 语句,该语句当前不适用于 else if 语句的最后几行中的当前错误。尽管我预计此声明仍然存在进一步的错误。变量选项来自终端中显示的菜单。因此,如果他们选择选项 1,则用户必须输入要写入 crontab 文件的数据。

if [ $choice -eq "1" ] then
echo "Enter the MINUTE"
read  minute

    if [ $minute -eq 0 ] then
        GLOBIGNORE=*
        minute="*"
        echo minute
    fi

echo "Enter the Hour"
read hour

    if [ $hour -eq 0 ] then
        GLOBIGNORE=*
        hour="*"
        echo hour
    fi

echo "Enter the Day"
read day

    if [ $day -eq 0 ] then
        GLOBIGNORE=*
        day="*"
        echo day
    fi

echo "Enter the Month"
read month

    if [ $month -eq 0 ] then
        GLOBIGNORE=*
        month="*"
        echo month
    fi

echo "Enter the weekday"
read weekday

    if [ $weekday -eq 0 ] then
        GLOBIGNORE=*
        weekday="*"
        echo weekday
    fi


echo $minute $hour $day $month $weekday " date > ~/testcron.log" > testcron.txt fi
elif [ $choice -eq "2" ]
then
    echo "Enter the Source and Destination Locations"
fi

【问题讨论】:

  • 请修正缩进。它应该可以帮助您识别代码的结构,例如fi属于哪个if
  • 发布整个声明(我看到多个if``s but only one fi`)。
  • bash 不是 python。缩进不影响操作顺序。您的所有 if 语句都没有终止 fi,因此实际上您只有一系列深度嵌套的 if 语句。
  • 已更新以包含 fi 语句,对于底部的格式问题表示歉意,由于某种原因,代码无法正确粘贴
  • 在编写 crontab 文件后,您在 fi 之前缺少换行符,这是您的代码中的问题还是这里的复制/粘贴错误?另外,对于基本的语法检查,请在打扰人类之前尝试shellcheck.net

标签: bash shell unix ubuntu if-statement


【解决方案1】:

您的代码有几个问题:

if [ $hour -eq 0 ] then
    GLOBIGNORE=*
    hour="*"
    echo hour
fi

一般来说(所有测试[])后面都缺少;

if [ $hour -eq 0 ]; then

回显小时不会打印 var hour 的值,而是单词 hour。更改为 echo "$hour"(是的,已引用)。此外,如果正确引用了 var,则无需将变量 GLOBIGNORE 设置为 *

这里的变量没有被引用,这是它失败(或需要 GLOBIGNORE)的原因:

echo $minute $hour $day $month $weekday

改为:

echo "$minute $hour $day $month $weekday"

同一行上的重定向是一个普通的>,它将清空文件。
如果要附加到文件,请执行以下操作:

echo "$minute $hour $day $month $weekday" "$(date >> ~/testcron.log)" >>testcron.txt

在那一行有一个不需要的额外的fi

此脚本可能会有所帮助:

get(){
    read -p "$1" "$2"
    if [ "$((${!2}))" -eq 0 ]; then
        eval "$2"="*"
        echo "${!2}"
    fi
}

read -p "Choice?:" choice

if [ "$choice" -eq "1" ]; then
    get "Enter the MINUTE"  minute
    get "Enter the Hour"    hour
    get "Enter the Day"     day
    get "Enter the Month"   month
    get "Enter the weekday" weekday
    date >> ~/testcron.log
    echo "$minute $hour $day $month $weekday" >> testcron.txt
elif [ "$choice" -eq "2" ]; then
    echo "Enter the Source and Destination Locations"
fi

【讨论】:

    【解决方案2】:

    你少了一个分号:

    if [ $choice -eq "1" ]; then
    

    if [ $choice -eq "1" ] 
    then
    

    需要分号或换行符,因为 命令 实际上是 [ 并且必须在 ] 之后终止,这只是 [ 的最后一个参数。

    这是旧的test(或[)语法,你也可以使用:

    if (( choice == 1 ))
    then
    

    【讨论】:

      猜你喜欢
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 2016-07-05
      相关资源
      最近更新 更多