Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Shell aliases don’t always evaluate commands at runtime #176

Open
luantranminh opened this issue Sep 16, 2024 · 0 comments
Open

Shell aliases don’t always evaluate commands at runtime #176

luantranminh opened this issue Sep 16, 2024 · 0 comments
Labels

Comments

@luantranminh
Copy link
Owner

I learned something cool about shell aliases today. Sometimes they don't work the way you expect, especially when you're trying to use live command results inside them.

I had this Git alias:

alias gitpul="git pull origin $(git branch --show-current)"

I thought it would always pull my current branch. But it kept trying to pull the same old branch, no matter which branch I was on.
This happened because aliases in the shell evaluate any command substitutions ($()) when the shell starts, not when the alias is executed.

The fix: Use single quotes for the alias definition and escape the inner double quotes:

alias gitpul='git pull origin "$(git branch --show-current)"'

This delays the command substitution until the alias is actually executed, ensuring it always pulls the current branch.


Tip

Single quotes in shell scripting delay evaluation because of how the shell interprets them. Let's break this down:

  1. Double quotes (" "):
  • Allow variable and command substitution.
  • The shell expands variables and executes commands inside double quotes immediately.
  1. Single quotes (' '):
  • Treat everything inside as literal text.
  • No expansions or substitutions occur inside single quotes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant