简体   繁体   中英

Combine multiple parameter expansion operations in bash

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^^}

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.

bash中无法进行嵌套参数扩展,或者您可以使用[ ... ]运算符检查变量是否设置:

[ -z "$ENV" ] && echo "DEFAULT" || echo ${ENV^^}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM