Gabriel Gabriel - 4 years ago 124
Git Question

Bash expand variable in Git Bash on Windows not working?

Why is the following not working (no output):

fileRe="-regex '.*\.h'"
find "." -type f $fileRe


but the following works (and outputs results)

find "." -type f -regex '.*\.h'


Working with:
/c/Program Files/Git/bin/bash


this is not intuitive?

Answer Source

When you type find "." -type f -regex '.*\.h' and press Enter, the shell interprets the single quotes as the enclosing markers of a fixed string, and uses the enclosed value as the argument to pass to the find command.

In contrast with that, when you set fileRe="-regex '.*\.h'", the value within the double-quotes is stored as-is (after variable expansion), and the embedded single-quotes are taken literally.

And then, when you pass $fileRe to find, the value is taken as it was stored, it is not reinterpreted, so the literal single-quotes in the value remain literal single-quotes.

To achieve what you want, you can use a Bash array instead:

fileRe=(-regex '.*\.h')
find . -type f "${fileRe[@]}"

The difference in this version from yours is that the arguments passed to find are -regex and .*\.h. The single-quotes are not part of the value, because they were used when creating the value of the array, and they were not embedded in a double-quoted expression.

This behavior is the same in any Bash shell, regardless of the operating system.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download