Recently I decided to read a bit more on the bash built-ins declare
, local
, and readonly
, which led me to switch from:
local variable_name
variable_name='value'
readonly variable_name
To:
variable_name='value'
declare -r variable_name
This change cut down the number of lines written and allowed me to set a few attributes, like telling bash that the value of a variable is an integer, which was nice. However, while creating a function that will serve as an alias for cURL, I noticed that variables inside an array never expand if I use declare
, but expand just fine with local
and readonly
.
Here is an example:
#!/usr/bin/env bash
set -o errexit -o errtrace -o pipefail -o nounset
IFS=$'\n\t'
curl() {
curl_version="$(command curl --version | awk 'NR==1 {print $2}')"
declare -r curl_version
curl_args=(
--user-agent "curl/${curl_version}"
--silent
--fail
)
command curl "${curl_args[@]}" \
"${@}"
}
curl --url 'https://httpbin.org/get'
Because the variables do not expand for whatever reason, the --user-agent
part of the array makes the script exit with an error, since as far as bash knows, this is an unbound variable, and those are not allowed because of set -o nounset
.
I have been trying to get this to work for a few days now, so I guess it is time to throw the towel and ask for help. Can anyone point me in the right direction to understand what I am doing wrong, please?
EDIT:
Forgot to mention, but the variable does expand if I declare it in the same line, like declare -r variable_name
. The problem is, if I do that, I hit SC2155 from ShellCheck, hence why I am trying to declare after the value is set.
echo $curl_version;
there?