How to create a command shortcut in BASH or ZSHRC shells?

5,487

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"
}
Share:
5,487

Related videos on Youtube

MKM
Author by

MKM

Updated on September 18, 2022

Comments

  • MKM
    MKM over 1 year

    I know how to create an alias or a PATH 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 and svn commands work

    • f p
      f p about 9 years
      What's wrong in creating a bash script?
    • ott--
      ott-- about 9 years
      In bash: alias alog='tail -f /var/log/apache2/error_log'
    • kenorb
      kenorb about 9 years
      Bash 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
      MKM about 9 years
      You guys are right, I thought alias was only to navigate with cd in front.. do you want to post the answer?
  • glenn jackman
    glenn jackman about 9 years
    You have to quote all those $1 -- hs() { history | grep "$1"; } -- otherwise the argument is subject to word splitting and filename expansion: for example hs "foo bar" results in grep: bar: No such file or directory (see gnu.org/software/bash/manual/bashref.html#Shell-Expansions)