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

标签 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 语句中一切正常,但在尝试解决最后几行的错误时,我放弃了我最初的想法并且偏离了解决这个问题的距离。

最佳答案

用现代 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-only(因此,对于带有 #!/bin/bash shebang 的脚本,或者由具有相同扩展名的 shell 显式运行的脚本,例如ksh 或 zsh)

关于linux - 如何在 if else 语句的末尾修复此表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54134881/

相关文章:

linux - 在 bash 中使用 find 命令查找多个不同类型的文件

linux - 尝试更改我的 Ubuntu 桌面的屏幕分辨率

linux - 创建 ImageMagick Linux 脚本

bash - 与 Bash 类似的 R 命令行的 Vi 键绑定(bind)

bash - 搜索字符串,如果匹配则添加

bash 非数组 ${!name[@]} 参数扩展困惑

linux - 获取两个标记模式之间的线,其中结束模式位于特定列中

linux - 向 255.255.255.255 广播 UDP 数据包

python - 通过 web 服务进行 crm 集成的 evolution 插件

linux - 在软链接(soft link)链接的目录中查找文件