Since you are using Bash, you may make use of associative arrays (introduced in bash-4.0-alpha
1).
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.
case .. esac
statement checking the value of a positional parameter such as$1
, or you could use aselect
statement to present a list of options if one is not provided.