Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over command-line argument pairs

I have a more than 400 coordinates that I want to pass as an argument into a string, but i don't know how to pass the first argument as "lat" and second argument as "lng" and so on for the rest.

Say I was passing in this

./test 1 2 3 4

I want my output to be

coordinate: {lat: 1, lng: 2}
coordinate: {lat: 3, lng: 4}

This is what I have so far, but obviously this isn't how it's done.

for i in $@
do

    echo "coordinate: {lat: $i, lng: $i}"

done
like image 591
Shakar Sardar Avatar asked Dec 14 '22 22:12

Shakar Sardar


2 Answers

#!/usr/bin/env bash
while (( "$#" >= 2 )); do
  echo "coordinate: {lat: $1, lng: $2}"
  shift 2
done

Note that shift; shift is in many circles preferred over shift 2, as it works even there's only one argument left; shift 2 is safe above only because we're comparing $# to ensure that there will always be two or more arguments.

like image 165
Charles Duffy Avatar answered Dec 16 '22 10:12

Charles Duffy


You do not need a loop:

printf "coordinate: {lat: %s, lng: %s}\n" "$@"

And rename your script before putting in your path (something like /usr/local/bin), since test is a builtin function.

like image 28
Walter A Avatar answered Dec 16 '22 11:12

Walter A