如何在unix中找到数组中的最后一个元素?

时间:2013-06-18 10:00:33

标签: arrays unix if-statement ksh

如何在unix中找到数组中的最后一个元素?我需要找到数组中的最后一个元素来执行if-statement

    if [ #last_array ];
    then
     #Do something
    fi 

我该怎么办?我可以在if中只放一个参数吗?我只想要最后一个数组做某事

2 个答案:

答案 0 :(得分:1)

$ set -A arr 1 2 3 4 5
$ let LAST_ELEMENT=${#arr[*]}-1
$ echo ${arr[$LAST_ELEMENT]}

答案 1 :(得分:0)

我认为类似的东西可以成功。我知道,这不是很好,但不能用其他好的方式思考:

#!/bin/bash

a=("hello" "bye" "another" "word")
i=0

num_words=${#a[@]}
echo "there are $num_words words"

for word in "${a[@]}"
do
        let i=i+1
        echo $i $word
        if [ $i -eq $num_words ]; then
                echo "last word!"
        fi
done

测试

$ ./test
there are 4 words
1 hello
2 bye
3 another
4 word
last word!
相关问题