Home > OS >  How to remove the last three elements of a list in bash?
How to remove the last three elements of a list in bash?

Time:11-17

This is how I do get all version tags of an image in a custom docker registry:

r=`curl -sS "$registry/v2/" \
    -o /dev/null \
    -w '%{http_code}:%header{www-authenticate}'`
http_code=`echo "$r" | cut -d: -f1`
curl_args=(-sS -H 'Accept: application/vnd.docker.distribution.manifest.v2 json')
curl_args =(-u "$creds")
tags=`curl "${curl_args[@]}" "$registry/v2/$image/tags/list"  | jq -r .tags[] | sort -V`

The result could be something like:

1.0.0
1.1.2
1.2.0
1.2.1
1.0.1
1.1.0
1.1.1
1.2.1

Now I just want to get all tags except the newest three and if there are less than three tags, the result should be empty. So in this example I need to get

1.0.0
1.0.1
1.1.0
1.1.1
1.1.2

I tried to use unset $tags[-3], but I think I do not get an array returned by the last curl call. So is sort -V working at all with this syntax?

CodePudding user response:

Use sort within jq, then index using : to get a range (negative indices count from the end).

jq -r '.tags | sort[:-3][]'

You can emulate version sorting by splitting the version string at the dots, and converting the items to numbers (works for the kind of version strings given in the sample).

jq -r '.tags | sort_by(./"." | map(tonumber))[:-3][]'

Output:

1.0.0
1.0.1
1.1.0
1.1.1
1.1.2
  • Related