Search code examples
shellzshaliasquoting

How to use wildcard * in alias


# first examle
> alias gostyle="goimports -w $(find . -type f -name '*.go' -not -path './vendor/*')"
> alias gostyle
gostyle=$'goimports -w / gofiles /'

# second example
> alias gostyle="goimports -w $(find . -type f -name 'main.go' -not -path './vendor/*')"
> alias gostyle
gostyle='goimports -w ./main.go'

Why in first example I have $ in the front of command. How I can use wildcard * right in alias. Why I have permission denied when I use first alias


Solution

  • Because you are using double quotes instead of single, the $(find ...) is executed once, at the time you define your alias. You end up with an alias with a hard-coded list of files.

    The trivial fix is to use single quotes instead of double (where obviously then you need to change the embedded single quotes to double quotes instead, or come up with a different refactoring); but a much better solution is to use a function instead of an alias. There is basically no good reason to use an alias other than for backwards compatibility with dot files from the paleolithic age of Unix.

    gostyle () {
        goimports -w $(find . -type f -name '*.go' -not -path './vendor/*') "$@"
    }
    

    (Unfortunately, I am not familiar with goimports; perhaps it needs its argument to be double quoted, or perhaps you should add one -w for each result that find produces. Or perhaps you actually want

    gostyle () {
        find . -type f -name '*.go' -not -path './vendor/*' -print0 |
        xargs -0 goimports -w "$@"
    }
    

    where you might or might not want to include "$@".)