halpdoge
halpdoge

Reputation: 712

Alias in bash_profile executes by itself

I have set up an alias in ~/.bash_profile as follows:

alias lcmt="git show $(git log --oneline | awk '{print $1;}' | head -n 1)"

However, whenever I open a terminal window, I see:

fatal: Not a git repository (or any of the parent directories): .git

I have been able to narrow it down to that particular alias because when I comment it out, there's no error message. Why does it evaluate by itself on OS X? Can I prevent it from doing so?

Upvotes: 2

Views: 252

Answers (2)

Gordon Davisson
Gordon Davisson

Reputation: 126038

Shell functions are better than aliases in a number of ways, including that there's no quoting weirdness like there is with aliases. Defining a shell function to do this is easy:

lcmd() { git show $(git log --oneline | awk '{print $1;}' | head -n 1); }

I'd make two other recommendations, though: put double-quotes around the $( ) expression, and have awk take care of stopping after the first line:

lcmd() { git show "$(git log --oneline | awk '{print $1; exit}')"; }

Upvotes: 4

janos
janos

Reputation: 124804

The $(...) inside a double-quoted expression gets executed at the time of the assignment, the creation of the alias. You can avoid that by escaping the $ of the $(...). And you want to do the same thing for the $1 inside the awk command:

alias lcmt="git show \$(git log --oneline | awk '{print \$1}' | head -n 1)"

Upvotes: 6

Related Questions