Search code examples
bashshellcommandcommand-substitution

run command inside of ${ curly braces


I want to alias cd so that it takes me to the root of my current git project, and if that can't be found it takes me to my normal home dir.

I am trying to set HOME to either the git root or, if that can't be found, my normal home variable.

alias cd='HOME="${$(git rev-parse --show-toplevel):-~}" cd'

It doesn't work though.


Solution

  • You can't run a command inside ${}, except in the fallback clause for when a value is not set (in POSIX sh or bash; might be feasible in zsh, which allows all manner of oddball syntax).

    Regardless, far fewer contortions are needed if using a function:

    # yes, you can call this cd, if you *really* want to.
    cdr() {
       if (( $# )); then
         command cd "$@"
       else
         local home
         home=$(git rev-parse --show-toplevel 2>/dev/null) || home=$HOME
         command cd "$home"
       fi
    }
    

    Note:

    • Using a function lets us test our argument list, use branching logic, have local variables, &c.
    • command cd is used to call through to the real cd implementation rather than recursing.