Search code examples
bashmacoscdquoting

cd to a path containing spaces stored in a variable in Bash on macOS


I have

x="/dir 1"
y=/dir\ 2

When I do cd $x or cd $y I get an error. I don't want to do cd "$x" because

  1. I don't know which variables contain a path with spaces
  2. It is inconvenient

Any workaround?


Solution

  • There is a shell option that tells Bash to check if the argument to cd is a variable that contains a path:

    shopt -s cdable_vars
    y='/dir 2'
    cd y
    

    where cd y is equivalent to cd "$y".

    From the manual:

    cdable_vars
    If this is set, an argument to the cd builtin command that is not a directory is assumed to be the name of a variable whose value is the directory to change to.


    Recent versions of bash-completion check if the shell option is set and offer to complete variable names for cd, but to get this to work, the shell option has to be set before the completion is loaded.

    The default completion setting for cd is

    complete -F _cd -o nospace cd pushd
    

    To add variable completion to this, it has be changed to

    complete -v -F _cd -o nospace cd pushd