I want to create an alias in bash, such that
git diff somefile
becomes
git diff --color somefile
But I don't want to define my own custom alias like
alias gitd = "git diff --color"
because if I get used to these custom alias, then I loose the ability to work on machines which don't have these mappings.
Edit: It seems bash doesn't allow multi-word alias. Is there any other alternative solution to this apart from creating the alias?
A Bash alias is essentially nothing more than a keyboard shortcut, an abbreviation, a means of avoiding typing a long command sequence. If, for example, we include alias lm="ls -l | more" in the ~/. bashrc file, then each lm [1] typed at the command-line will automatically be replaced by a ls -l | more.
BASH Alias is a shortcut to run commands using some mapping. It is a way to create some shortcut commands for repetitive and multiple tasks. We create an alias in a BASH environment in specified files. We can also incorporate BASH functions, variables, etc to make the Alias more programmatic and flexible.
In the bash syntax no spaces are permitted around the equal sign. If value contains spaces or tabs, you must enclose value within quotation marks. Unlike aliases under tcsh, a bash alias does not accept an argument from the command line in value.
To create a smarter alias for a command, you have to write a wrapper function which has the same name as that command, and which analyzes the arguments, transforms them, and then calls the real command with the transformed arguments.
For instance your git function can recognize that diff is being invoked, and insert the --color argument there.
Code:
# in your ~/.bash_profile
git()
{
if [ $# -gt 0 ] && [ "$1" == "diff" ] ; then
shift
command git diff --color "$@"
else
command git "$@"
fi
}
If you want to support any options before diff and still have it add --color, you have to make this parsing smarter, obviously.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With