1

我有一个数组,其中包含一些采用以下格式的亚马逊 ec2 卷快照的 UTC 创建时间:2013-08-09T14:20:47.000Z

我试图找出一种方法来比较数组的元素以确定哪个是最旧的快照并在 Bash 4 中将其删除

我现在拥有的当前代码:

#creates a count of all the snapshot volume-id's and deletes oldest snapshot if 
#there are more than 5 snapshots of that volume

declare -A vol_id_count=( ["id_count"]="${snapshot_vols[@]}" )
check_num=5

for e in ${vol_id_count[@]}
do
  if (( ++vol_id_count[$e] > $check_num ))
  then
    echo "first nested if works"
    #compare UTC times to find oldest snapshot
    #snapshot_time=${snapshot_times[0]}

    #for f in ${snapshot_times[@]}
    #do
    #  time= date --date="$snapshot_time" +%s
    #  snapshot_check=${snapshot_times[$f]}
    #  echo "check: "$snapshot_check
    #  check= date --date="$snapshot_check" +%s

    #  if [[ "$snapshot_time" -gt "$snapshot_check" ]]
    #  then
    #    snapshot_time=$snapsnapshot_check
    #    echo "time: "$snapshot_time
    #  fi
    #done

    #snapshot_index=${snapshot_times[$snapshot_time]}
    #aws ec2 delete-snapshot --snapshot-id "${snapshot_ids[$snapshot_index]}"
  fi
done

我有第一个 for 循环和 if 语句,用于检查某个卷的快照是否超过 5 个,但我正在挠头,试图弄清楚如何比较 UTC 字符串。第二个关联数组会做我想知道的伎俩吗?

4

2 回答 2

2

这是我的做法:使用sort.

dates=(
    2013-08-09T14:20:47.000Z
    2013-08-09T14:31:47.000Z
    )

latest=$(for date in ${dates[@]}
do
    echo $date
done | sort | tail -n 1)

echo $latest # outputs "2013-08-09T14:31:47.000Z"

这显然只是一个示例脚本,可以根据需要进行修改 - 它可以很容易地变成一个函数,例如:

function latest() {
    local dates="$@"
    for date in ${dates[@]}
    do
        echo $date
    done | sort | tail -n 1
}

latest ${dates[@]} # outputs "2013-08-09T14:31:47.000Z"
于 2013-08-09T15:51:06.810 回答
0

如果您已经有一个数组,则无需使用循环来打印项目。单个回显将起作用(但仅当文件名中没有空格时):

oldest=`echo "${snapshot_times[@]}" | tr ' ' '\12' | sort -r | tail -1)`

如果这些“时间戳”来自文件名本身,只需ls在管道中使用:

snapshot_dir=/some/path/to/snapshots
count=`ls -1 $snapshot_dir/ | wc -l`  # get count of snapshots

# expunge the oldest snapshot if there are more than 5
if (( count > 5 )); then
  oldest_name=`(cd $snapshot_dir ; ls -1 ) | sort | head -1`
  oldest_file="$snapshot_dir/$oldest_name"
  [[ -f "$oldest_file" ]] && {
    echo "Purging oldest snapshot: $oldest_file"
    rm -f $oldest_file
  }
fi
于 2013-08-09T21:02:33.517 回答