【问题标题】:Bash - How to check if all array values are greater than specific number [closed]Bash - 如何检查所有数组值是否大于特定数字[关闭]
【发布时间】:2021-03-08 16:07:16
【问题描述】:

如何检查所有数组值是否大于bash中的特定数字

【问题讨论】:

标签: bash shell


【解决方案1】:

这是一个设计过度的答案,旨在像其他语言中的函数式方法一样工作:

gt() { (( $1 > $2 )); }

all() {
  local -n _ary=$1
  local func=$2
  shift 2
  for elem in "${_ary[@]}"; do
    "$func" "$elem" "$@" || return 1
  done
}

array=(5 6 7 8 9 10)

if all array gt 4;  then echo true; else echo false; fi   # true
if all array gt 40; then echo true; else echo false; fi   # false

这使用 nameref 因此需要 bash 版本 4.3+

【讨论】:

    【解决方案2】:
    #! /bin/bash
    number=42
    arr=(56 120 74 52 12)
    
    all_greater=1
    for element in "${arr[@]}" ; do
        if (( element <= number )) ; then
            all_greater=0
        fi
    done
    if (( all_greater )) ; then
        echo All values are greater.
    else
        echo Some values aren\'t greater.
    fi
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-18
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-24
      相关资源
      最近更新 更多