Friday, March 29, 2013

Disable wildcard expansion when calling BASH scripts

This is a rarely needed, but very useful item. I wanted to create a script that I could pass wildcards into. But bash will automatically expand wildcards before the script can get them, so running

$ myscript.sh *

will call myscript with a bunch of filenames instead of the "*" character.

The solution is to create an alias to disable globbing:

noglob_helper() {
    "$@"
    case "$shopts" in
        *noglob*) ;;
        *) set +f ;;
    esac
    unset shopts
}

alias noglob='shopts="$SHELLOPTS"; set -f; noglob_helper'
Now you can preface your script with the alias and the wildcards will not be expanded:

$ noglob myscript.sh *

This code is from Simon Tatham's home page (the author of PuTTY among other things) http://www.chiark.greenend.org.uk/~sgtatham/aliases.html

No comments:

Post a Comment