Ubuntu – How to set an alias to a terminal line

aliasbashcommand line

I want to easily set an alias git-go to this terminal line:

git commit -m "init "; git push; git status

So when I enter git-go this line should enter.

How can I do that? The answers I seen only cover alias of a command without parameters. But I want to set an alias to an arbitrary terminal line.

Best Answer

You do this the same way you would set any alias.

alias git-go='git commit -m "init "; git push; git status'

The situation where it gets tricky is not when an alias runs a command and passes arguments to that command, nor even when an alias runs multiple commands separated by ;, but instead is when you want an alias to accept and use its own command-line arguments.

For example, anything you write after the name of that alias will be pasted onto the end, and thus passed as command-line arguments to the third git command, after git status. (Really it's not so much that the following text is pasted onto the end, as much as it is that the following text is left alone and the alias name is replaced with its definition.)

So you can run your alias without arguments, which works, and the last command is git status:

git-go

Or you can run it with arguments that you want passed to git status. For example, when you run it this way, the last command is git-status --show-stash:

git-go --show-stash

What you cannot do with an alias in Bash (and other Bourne-style shells) is to make the alias accept command-line arguments and place them elsewhere than the end.

For example, suppose you wanted git-go to accept an argument that it uses for the commit message. You would not be able to write this as an alias. The solution would be to write it as a shell function instead:

git-go() { git commit -m "$1"; git push; git status; }

In the definition of a shell function, the positional parameters $1, $2, and so forth hold the values of the command-line arguments passed to the shell function. Aliases have no functionality that corresponds to this, because alias expansion is really a form of macro processing, taking place very early, when the shell parses a command.

You can, of course, write it as a shell function even if you don't need to use positional parameters in the definition, as Videonauth suggests.