- A "local" variable, that will be local to the function
var=foo
value="b a r"
declare "${var}=${value}"- A "global" vairable, that will be set outside a function
var=foo
value="b a r"
export -n "${var}=${value}" # Compatible with bash 3.2, use this one. Does not work on arrays prior to bash 4.2
# https://stackoverflow.com/q/10806357/4166604
# declare -g "${var}=${value}" # Not compatible with bash 3.2, only bash 4.2 or newer- An exported variable, that will be inherited by child processes
var=foo
value="b a r"
export "${var}=${value}"I want to conditionally set an array when it is unset, I have made a one liner for an array, using a function o replicate : ${FOO=BAR} for arrays:
function set_array_default()
{
local default="$1"
shift 1
if ! declare -p $default &> /dev/null; then
local IFS=''
if [ "${BASH_VERSINFO[0]}${BASH_VERSINFO[1]}" -ge "42" ]; then
declare -ag "${default}=()"
else
eval "${default}=()"
fi
for (( i=0; $#; i++ )); do
read -r "${default}[$i]" <<< "${1}"
shift 1
done
fi
}
set_array_default foo bar "B A R"