Home > Back-end >  Set bash variable one liner from if else
Set bash variable one liner from if else

Time:11-18

TOKEN=$(if [[ $TOKEN ]] then echo $TOKEN else cat ./cloud/token fi)

So I'm trying to set the variable TOKEN. This might of been set previously in which case I'd like for that value to be used and if not I'd like for it to be assigned by catting a file.

The above doesn't work as my skills in bash are lacking!

CodePudding user response:

You can simplify this by using bash's support for default parameter values. From the bash docs:

   ${parameter:-word}
          Use Default Values.  If parameter is unset or null, the expansion of 
          word is substituted.  Otherwise, the value of parameter is substituted.

For your example, you can do this:

TOKEN=${TOKEN:-$(cat ./cloud/token)}

CodePudding user response:

In this particular case, I would use parameter substitution and specify a default value which is used when the variable is not defined:

TOKEN=${TOKEN-$(cat ./cloud/token)}

CodePudding user response:

TOKEN=$([ -n "$TOKEN" ] && echo "$TOKEN" || cat ./cloud/token)

CodePudding user response:

I think that semicolons are necessary.

TOKEN=$(if [[ $TOKEN ]]; then echo $TOKEN; else cat ./cloud/token; fi)

CodePudding user response:

You can use :

: ${TOKEN:=$(cat ./cloud/token)}

CodePudding user response:

TOKEN=$(if [ -z "${TOKEN}" ]; then cat ./cloud/token; else echo "${TOKEN}"; fi)
  •  Tags:  
  • bash
  • Related