How to create a command shortcut in BASH or ZSHRC shells?
It isn't true that alias
is used only to navigate folders. It can be used for other commands as well (that's why it's called alias
).
In example:
alias arestart='sudo apachectl restart'
alias alog='tail -f /var/log/apache2/error_log'
and place them in ~/.bashrc
or ~/.bash_profile
.
Or you may want to put all your alias definitions into a separate file like
~/.bash_aliases
(check bash-doc/examples in the bash-doc package for details). And you can include alias definition in your ~/.bashrc
as follow:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
Alternatively you can use bash functions which works similar to aliases (which supports arguments). For example:
# Restart apache
# Usage: arestart
arestart() {
sudo apachectl restart
}
# Show log via tail.
# Usage: alog (file)
alog() {
tail -f "$1"
}
# Find file
# Usage: ff (file)
ff() {
find . -name "$1"
}
# Search in command history.
# Usage: hs (string)
hs() {
history | grep "$1"
}
Related videos on Youtube
MKM
Updated on September 18, 2022Comments
-
MKM over 1 year
I know how to create an
alias
or aPATH
however those are both used to navigate folders.How would you create a shortcut to say quickly type the following commands every time?
alog =
tail -f /var/log/apache2/error_log
arestart =
sudo apachectl restart
So a shortcut similar to how
git
andsvn
commands work-
f p about 9 yearsWhat's wrong in creating a bash script?
-
ott-- about 9 yearsIn bash:
alias alog='tail -f /var/log/apache2/error_log'
-
kenorb about 9 yearsBash
alias
is not only to navigate folders, you can create whatever you want, that is for. So what's wrong with:alias arestart ='sudo apachectl restart'
? -
MKM about 9 yearsYou guys are right, I thought
alias
was only to navigate withcd
in front.. do you want to post the answer?
-
-
glenn jackman about 9 yearsYou have to quote all those
$1
--hs() { history | grep "$1"; }
-- otherwise the argument is subject to word splitting and filename expansion: for examplehs "foo bar"
results ingrep: bar: No such file or directory
(see gnu.org/software/bash/manual/bashref.html#Shell-Expansions)