Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple parameter expansion operations in bash

Tags:

bash

shell

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^^}
like image 930
Djabx Avatar asked Mar 28 '18 07:03

Djabx


2 Answers

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.

like image 65
Inian Avatar answered Oct 06 '22 01:10

Inian


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^^}
like image 40
oliv Avatar answered Oct 06 '22 01:10

oliv