ZSH alias with parameter
ShellZshAliasZshrcShell Problem Overview
I am trying to make an alias with parameter for my simple git add/commit/push.
I've seen that a function could be used as an alias, so I tried but I didn't make it.
Before I had:
alias gitall="git add . ; git commit -m 'update' ; git push"
But I want to be able to modify my commits:
function gitall() {
"git add ."
if [$1 != ""]
"git commit -m $1"
else
"git commit -m 'update'"
fi
"git push"
}
Shell Solutions
Solution 1 - Shell
If you really need to use an alias with a parameter for some reason, you can hack it by embedding a function in your alias and immediately executing it:
alias example='f() { echo Your arg was $1. };f'
I see this approach used a lot in .gitconfig aliases.
Solution 2 - Shell
You can't make an alias with arguments*, it has to be a function. Your function is close, you just need to quote certain arguments instead of the entire commands, and add spaces inside the []
.
gitall() {
git add .
if [ "$1" != "" ] # or better, if [ -n "$1" ]
then
git commit -m "$1"
else
git commit -m update
fi
git push
}
*: Most shells don't allow arguments in aliases, I believe csh and derivatives do, but you shouldn't be using them anyway.
Solution 3 - Shell
I used this function in .zshrc file:
function gitall() {
git add .
if [ "$1" != "" ]
then
git commit -m "$1"
else
git commit -m update # default commit message is `update`
fi # closing statement of if-else block
git push origin HEAD
}
Here git push origin HEAD
is responsible to push your current branch on remote.
From command prompt run this command: gitall "commit message goes here"
If we just run gitall
without any commit message then the commit message will be update
as the function said.
Solution 4 - Shell
"git add ."
and the other commands between "
are just strings for bash, remove the "
s.
You might want to use [ -n "$1" ]
instead in your if body.
Solution 5 - Shell
I tried the accepted answer (Kevin's) but was getting the following error
defining function based on alias `gitall'
parse error near `()'
Hence changed the syntax to this, based on the git issue and it worked.
function gitall {
git add .
if [ "$1" != "" ]
then
git commit -m "$1"
else
git commit -m update
fi
git push
}
Solution 6 - Shell
Aliases with parameters
TL;DR:
Use an alias with parameter(s):
alias foo='echo bar'
# works:
foo 1
# bar 1
foo 1 2
# bar 1 2
Expained
(Space-separated) Characters after an alias will be treated as parameter(s) in the sequence you write them.
They cannot be ordered or changed as you can with functions. E. g. putting arguments into the middle of command via alias is indeed possible with the help of a function or a subshell: See @Tom's answer
This behaviour is similar to bash
.