Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create multi-word alias in bash?

Tags:

git

bash

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?

like image 516
Sudar Avatar asked Apr 16 '12 06:04

Sudar


People also ask

How do you create aliases in bash?

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.

Can you use an alias in a bash script?

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.

Can bash alias have spaces?

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.


1 Answers

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.

like image 90
Kaz Avatar answered Sep 28 '22 17:09

Kaz