ramius
ramius

Reputation: 211

Bash - build URL query string by parsing script command arguments

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.

Upvotes: 4

Views: 2564

Answers (2)

unconditional
unconditional

Reputation: 7656

Every iteration you have to check the previous arg to see if it was a switch, not a value:

#!/bin/bash

set -e

echo "${@}"

prev_arg=""
query_string=""
for arg in "${@}" ; do
  if [[ $arg == -* ]] ; then

    # Current arg is a switch and the previous one was also a switch 
    # which means the value for it is blank
    if [[ $prev_arg == -* ]] ; then
      query_string+="blank&"
    fi

    query_string+="${arg}="
  else
    query_string+="${arg}&"
  fi

  prev_arg="$arg"
done

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

This produces the following output:

something -v -s somethingelse
e=something&v=blank&s=somethingelse

Upvotes: 1

Benutzer193
Benutzer193

Reputation: 140

How about:

#!/bin/bash

set -e

echo "${@}"

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

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

Upvotes: 2

Related Questions