1

I would like to be able to pass in what environment when script is run. Like script.sh dev ($dev would populate appropriate URL in curl command in script).
Maybe even print the environment as options to pass?

#!/bin/bash

# Environment/URL
dev=myurl.myco.com
tst=myurl.myco.com
tst02=myurl.myco.com
tst03=myurl.myco.com
qa01=myurl.myco.com

request=`curl -L -k -H 'Content-Type:application/x-www-form-urlencoded' -H 'cache-control:no-cache' -X  https://$tst/bla/bla/bla/bla 2>/dev/null`
  • You could use a case .. esac statement checking the value of a positional parameter such as $1, or you could use a select statement to present a list of options if one is not provided. – DopeGhoti May 14 at 16:26
1

Since you are using Bash, you may leverage associative arrays (introduced in bash-4.0-alpha1).

You can define the script:

#!/bin/bash

declare -A urls

urls[dev]=dev.example.com
urls[tst]=test.example.com

request="$(curl ...  https://"${urls["$1"]}"/foo/bar ...)"

And invoke it as:

script dev

The first positional parameter ($1) will be used as the key for retrieving a URL from the urls array.

As a (more user friendly) variation, as suggested by DopeGhoti, script may be:

#!/bin/bash

declare -A urls

urls[dev]=dev.example.com
urls[tst]=test.example.com

select opt in "${!urls[@]}"; do
    [ ! -z "$opt" ] && break
done

request="$(curl ... https://"${urls["$opt"]}"/foo/bar ...)"

Which is meant to be invoked as:

script

The select command presents the user with the list of the keys defined for the urls array and ensures that a valid key is chosen.

Finally, as a way to separate concerns, you may store your URLs in a plain text file, here named urlfile, formatted as:

dev dev.example.com
tst test.example.com

and load its content into the script's urls array with a read loop:

#!/bin/bash

declare -A urls

while read -r label url; do
    urls["$label"]="$url"
done <urlfile

select opt in "${!urls[@]}"; do
    [ ! -z "$opt" ] && break
done

request="$(curl ... https://"${urls["$opt"]}"/foo/bar ...)"

Note: even if not necessary, I chose the $(...) command substitution syntax (instead of ` `) because it is generally more versatile.


1 With this commit from 2011. Bash 4.0+ is now widely available.

  • Note that non-numerical indices for shell arrays in bash require bash version 4 or later. – DopeGhoti May 15 at 15:23
  • @DopeGhoti Right, I didn't take the time to search for the version that introduced associative arrays. Question amended, thanks. – fra-san May 15 at 17:43
  • s/Question/Answer/ – fra-san May 16 at 6:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.