Bash - build URL query string by parsing script command arguments

Viewed 1822

I don't use Bash very frequently but I need to work on a bit of Bash that has to make a curl request to a web service with a query string tail built from command arguments contained in the script command arguments variable $@. So if the command argument string is something like -e something -v -s somethingelse, then the query string that must be produced is e=something&v=blank&s=somethingelse.

At the moment my test script looks like this:

#!/bin/bash

set -e

echo "${@}"

query_string=""
for arg in "${@}" ; do
  if [[ "${arg}" =~ "-" ]] ; then
    query_string+="${arg}="
  else
    if [ -z "${arg}" ] ; then
      query_string+="blank&"
    else
      query_string+="${arg}&"
    fi
  fi
done

echo "${query_string}" | tr -d '-'

and produces the incorrect output

e=something&v=s=somethingelse&

I'm not sure where I'm going wrong. Any suggestions would be appreciated.

2 Answers
Related