如何在if else语句的末尾修复此表达式?

时间:2019-01-10 18:31:26

标签: linux bash

我需要我的表达式能够根据输入将下一个间隔除以15。

还不是一个很好的编码器。尝试了很多((和[[以及类似的变体,但我觉得代码编写的方式是错误的。

printf "Enter a number: "
read DVSBL

let ISDIV=$DVSBL

    if [ $(( $ISDIV % 15 )) -eq 0 ]; then
        echo $DVSBL is divisible by 15.

    elif [[ $(( $ISDIV % 5 )) -eq 0 && $(( $ISDIV % 15 )) -ne 0 ]]; then
        echo $DVSBL is divisible by 5 and not by 15.

    elif [[ $(( $ISDIV % 3 )) -eq 0 && $(( $ISDIV % 15 )) -ne 0 ]]; then
        echo $DVSBL is divisible by 3 and not by 15.

#from and below is where i am having the most trouble

    else let NXTCLS=$NXTCLS
    $NXTCLS='(( $ISDIV / 15 ) + 1) * 15
        echo The next closest number to $DVSBL that is divisible by 15 is $NXTCLS
    fi

一切都可以在if语句中使用,但是在尝试解决最后两行中的问题时,我放弃了最初的想法,并且与解决这个问题相去甚远。

1 个答案:

答案 0 :(得分:1)

用现代bash编写,看起来可能像这样:

#!/usr/bin/env bash
#              ^^^^- this uses bash-only syntax, so shebang must not be #!/bin/sh
#                    or script must be run as ''bash scriptname'', not ''sh scriptname''

read -p "Enter a number: " isdiv

if (( (isdiv % 15) == 0 )); then
    echo "$dvsbl is divisible by 15."
elif (( (isdiv % 5) == 0 && (isdiv % 15) != 0 )); then
    echo "$isdiv is divisible by 5 and not by 15."
elif (( (isdiv % 3) == 0 && (isdiv % 15) != 0 )); then
    echo "$isdiv is divisible by 3 and not by 15."
else
    nxtcls=$(( ( (isdiv / 15) + 1) * 15 ))
    echo "The next closest number to $isdiv that is divisible by 15 is $nxtcls"
fi

let是1970年代的古老语法,切勿在新代码中使用。 $(( ))是POSIX指定的运行算术运算并替换其结果的方式。 (( ))仅适用于bash(因此,对于带有#!/bin/bash shebangs的脚本,或者由具有相同扩展名的shell(例如ksh或zsh)显式运行的脚本)