Monday, April 22, 2013

A working bashrc function without parameter expansion (globbing)

I have noticed that the function I had under my bashrc script to simplify the syntax of the find command wasn't actually working for all cases. When I passed asterisks for the search criteria, I was left with weird findings resulting from parameter expansion (globbing). Here is the failing function (from my home .bashrc):
function findf() {
   find $1 -name "$2" 2>/dev/null
}
Which doesn't work properly for the case mentioned above.

After meddling a little bit with this I was able to have a working "findf" by using an alias just to deactivate globbing (set -f) before calling the function (which I have renamed to avoid conflicting with the alias):
alias findf='set -f; findf_func'
function findf_func() {
   find $1 -name "$2" 2>/dev/null
   set +f
}
Deactivating globbing inside the function is not enough because the parameters will be expanded before the first line is executed.

After the find command finishes, globbing can be activated again with set +f.

No comments:

Post a Comment

Feel free to share your thoughts!