Reputation: 745
I've got a variable let's call it: ENV
that can be set or not, and if set it's in lowercase. According to my ENV
I would like to get some other variables (ex: URL_DEV
or URL_PROD
).
I know I can get my env in upper case with: ENV=${ENV^^}
and set default value with ENV=${ENV:-DEFAULT}
but is it possible to do it in one line ?
And generally, how can I combine bash operators on variables ?
I tried something like: ENV=${ENV^^:-DEFAULT}
but does not work as expected.
My solution is:
ENV=${ENV:-dev}
ENV=${ENV^^}
Upvotes: 16
Views: 8536
Reputation: 13239
Nested parameter expansion is not possible in bash
, alternatively you can check if the variable is set using [ ... ]
operator:
[ -z "$ENV" ] && echo "DEFAULT" || echo ${ENV^^}
Upvotes: 8
Reputation: 85530
You cannot achieve nested parameter expansion in bash
shell, though its possible in zsh
, so ENV=${ENV^^:-DEFAULT}
operation cannot be executed by default.
You could use a ternary operator in the form of case
construct in bash
shell as there is no built-in operator for it (? :
)
case "$ENV" in
"") ENV="default" ;;
*) ENV=${ENV^^} ;;
esac
But you shouldn't use upper case variable names for user defined shell variables. They are only meant for variables maintained by the system.
Upvotes: 9