Bash – How to store a path built with wildcards and containing with spaces into a variable

bashquotingshellvariablewildcards

Here's the situation (I'm on a Mac, OS X El Capitan):

# This works:

$ cd /Applications/Adobe\ Illustrator*/Cool\ Extras.localized/en_US/Templates/;

# These do not work:

$ INSTALL_DIR=/Applications/Adobe\ Illustrator*/Cool\ Extras.localized/en_US/Templates;
$ cd $INSTALL_DIR
# Moves me here: /Applications/Adobe

$ cd "$INSTALL_DIR"
-bash: cd: /Applications/Adobe Illustrator*/Cool Extras.localized/en_US/Templates: No such file or directory

$ cd "${INSTALL_DIR}"
-bash: cd: /Applications/Adobe Illustrator*/Cool Extras.localized/en_US/Templates: No such file or directory

My goal is to use $INSTALL_DIR in tar like so:

$ tar -xz $SOURCE_ZIP --strip-components 1 -C $INSTALL_DIR "*.ait";

Unfortunately, the -C (changing to destination directory) doesn't like the spaces in $INSTALL_DIR; if I use quotes, I can't get the * to work.

Is there an elegant way to handle this scenario?

Best Answer

When the * is not quoted the shell expands the argument list before running the command. It passes the expand argument list to the program.

When the * appears in a quoted string it is not expanded by the shell before being passed to the program.

Try expanding the path, assigning it to another variable, and then quoting the second variable when passing it as an argument.

Related Question