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 3 months
I know how to create an
aliasor aPATHhowever 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_logarestart =
sudo apachectl restartSo a shortcut similar to how
gitandsvncommands work-
f p almost 8 yearsWhat's wrong in creating a bash script? -
ott-- over 7 yearsIn bash:alias alog='tail -f /var/log/apache2/error_log' -
kenorb over 7 yearsBashaliasis 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 over 7 yearsYou guys are right, I thought
aliaswas only to navigate withcdin front.. do you want to post the answer?
-
-
glenn jackman over 7 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)