Iterating over pairs of command line arguments
I have over 400 coordinates that I want to pass as an argument to a string, but I don't know how to pass the first argument as "lat" and the second argument as "lng", etc. for the rest.
Let's say I went through this
./test 1 2 3 4
I want my conclusion to be
coordinate: {lat: 1, lng: 2}
coordinate: {lat: 3, lng: 4}
This is what I have so far, but obviously it is not.
for i in $@
do
echo "coordinate: {lat: $i, lng: $i}"
done
+3
source to share
3 answers
#!/usr/bin/env bash
while (( "$#" >= 2 )); do
echo "coordinate: {lat: $1, lng: $2}"
shift 2
done
Note that shift; shift
in many circles it is preferable shift 2
because it works even where there is only one argument left; shift 2
is safe above only because we are comparing $#
so that two or more arguments always exist.
+4
source to share