Search code examples
bashgitzshzshrc

Zsh alias not working, but command does work when pasted in terminal


I have an alias in my .zshrc file, called "housekeeping" like so:

alias housekeeping="git fetch -p && git branch -vv | grep ': gone]' | awk '{print $1}' | xargs git branch -d"

When I run this command, for some reason, I get the following output:

error: The branch '12795-add-ship-info-to-FAQ' is not fully merged.
If you are sure you want to delete it, run 'git branch -D 12795-add-ship-info-to-FAQ'.
error: branch '97167bb3f' not found.
error: branch '[origin/12795-add-ship-info-to-FAQ:' not found.
error: branch 'gone]' not found.
error: branch 'Edits' not found.
error: branch 'to' not found.
error: branch 'text' not found.

It looks like it's passing down the wrong arguments.

However when I run the exact same command directly from the terminal, I do get the desired result.

What am I doing wrong?


Solution

  • The problem is that inside the double quotes of your alias, $1 refers to the current first positional parameter of your shell. It's probably not set, so your alias is equivalent to

    alias housekeeping="... | awk '{print }' | xargs ..."
    

    after $1 expands to the empty string. As a result, the entire output of grep, not just the branch name, is fed to xargs, which treats any whitespace, not just newlines, as separating two arguments.

    You either need to escape the dollar sign (awk '{print \$1}') to make sure awk gets the correct script, or better yet, use a function instead of an alias to avoid the extra layer of quotes.

    housekeeping () {
      git fetch -p && git branch -vv | awk '/: gone]/ {print $1}' | xargs git branch -d
    }
    

    Note that I've replace the call to grep with a pattern in the awk script.