Set bash variable one liner from if else [duplicate]

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!


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

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-$(< ./cloud/token)}