Bash 脚本中的数组元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19720118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:28:11  来源:igfitidea点击:

Array elements in Bash scripts

bashif-statement

提问by camdixon

How can I use an if statement such as this to compare the element value to a variable. For example i'm going through an array of numbers, and checking the minimum. I'm having syntax problems.

如何使用诸如此类的 if 语句将元素值与变量进行比较。例如,我正在查看一组数字,并检查最小值。我有语法问题。

for ((j=0;j<$i;j++)); do
if [ "$array[$j]" -gt $min ]; then
        min=${array[$j]}
fi
done
echo The minimum number is $min

回答by Alexander L. Belikoff

Your ifstatement lacks thenclause:

你的if陈述缺少then条款:

if [ "$array[$j]" -gt $min ]; then
    min=${array[$j]}
fi

Also, in the true spirit of UNIX tools, consider something more elegant:

此外,本着 UNIX 工具的真正精神,考虑一些更优雅的东西:

min_elem=$(echo ${array[@]} | tr ' ' '\n' | sort -n | head -1)

回答by Idriss Neumann

Several comments:

几条评论:

  • See this answerto know when and how to protect your variables ;
  • -gtisn't the desired operator for getting the min
  • 请参阅此答案以了解何时以及如何保护您的变量;
  • -gt不是获得最小值所需的运算符

Here's a simple corrected example (just Bash without other commands) :

这是一个简单的更正示例(只是 Bash 没有其他命令):

#!/bin/bash

array=("1" "0" "2")
length="${#array[@]}"
min="${array[0]}"

for (( i=1 ; i < "$length"; i++)); do
    [[ ${array[$i]} -le $min ]] && min="${array[$i]}"
done

echo "The minimum number is $min"

EDIT : Test performed after the comment of gniourf_gniourf (see the comments)

编辑:在 gniourf_gniourf 评论后执行的测试(见评论)

[ ~]$ cat test.sh 
#!/bin/bash

array=("1" "0" "2")
m=${array[0]}; for i in "${array[@]:1}"; do ((i<m)) && m=$i; done
echo "The minimum number is $m"
[ ~]$ ./test.sh 
The minimum number is 0
[ ~]$ vi test.sh
[ ~]$ cat test.sh 
#!/bin/bash

array=("1" "0" "2")
m="${array[0]}"; for i in "${array[@]:1}"; do [[ $i -le $m ]] && m="$i"; done
echo "The minimum number is $m"
[ ~]$ ./test.sh 
The minimum number is 0
[ ~]$