我有一个数组,其中包含以下格式的几个amazon 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字符串。我想知道第二个关联数组会做出这个技巧吗?
答案 0 :(得分: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"
答案 1 :(得分:0)
如果您已有阵列,则无需使用循环打印项目。单个echo将起作用(但仅当文件名中没有空格时):
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