Skip to content

Instantly share code, notes, and snippets.

@smichaelsen
Last active December 19, 2016 08:23
Show Gist options
  • Save smichaelsen/497240d0759a7cebaf748b18804da9d9 to your computer and use it in GitHub Desktop.
Save smichaelsen/497240d0759a7cebaf748b18804da9d9 to your computer and use it in GitHub Desktop.
Bash: Variable variable name and default fallback

I'm trying to write in bash what would look like this in PHP 7:

echo ${$branch . '_SSH'} ?? $default_SSH;
  1. Check for a variable which has a variable name.
  2. Fall back to another variable if it doesn't exist.
  3. echo the result.

Is there an equivalent one liner in bash?

@etobi
Copy link

etobi commented Dec 18, 2016

this might be helping, although i'm not sure if it's the shortest/best solution::

SSH=$([ $BRANCH ] && echo $BRANCH"_SSH" || echo 'default_SSH') && echo ${!SSH}

however, always avoid to write "clever" code. be explizit and simple. Future-you will appreciate. ;-)

@smichaelsen
Copy link
Author

Thanks for the input. This doesn't kill it 100%. It checks if $BRANCH exists but not if the variable ${$BRANCH'_SSH'} exists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment