Question

What are your favorite bash aliases?

Posted September 2, 2016 43.8k views
Linux Basics

Bash aliases are awesome. They can save you keystrokes and give you shortcuts to some of your most used commands. I’ll share some of my own down in the answers.

What’s in your .bashrc file? What bash aliases have you found the most useful?

edited by AHA
5 comments
  • The publically shareable section of my bashrc file!

    # Reloads the bashrc file
    alias bashreload="source ~/.bashrc && echo Bash config reloaded"
    
    # Open nano and make backup of original file. Useful for config files and things you don't want to edit the original
    function nanobk() {
        echo "You are making a copy of $1 before you open it. Press enter to continue."
        read nul
        cp $1 $1.bak
        nano $1
    }
    
    # Clear DNS Cache
    
    # Still need testing on this one
    
    alias flushdns="sudo /etc/init.d/dns-clean restart && echo DNS cache flushed"
    
    
    # Get IPs associated with this site
    
    # Work to dynamically list all interfaces. Will add later. 
    # Currently only uses the hardcoded interface names
    
    function myip()
    {
        extIp=$(dig +short myip.opendns.com @resolver1.opendns.com)
    
        printf "Wireless IP: "
        MY_IP=$(/sbin/ifconfig wlp4s0 | awk '/inet/ { print $2 } ' |
          sed -e s/addr://)
        echo ${MY_IP:-"Not connected"}
    
    
        printf "Wired IP: "
        MY_IP=$(/sbin/ifconfig enp0s25 | awk '/inet/ { print $2 } ' |
          sed -e s/addr://)
        echo ${MY_IP:-"Not connected"}
    
        echo ""
        echo "WAN IP: $extIp"
    
    }
    
    
    # Syntax: "repeat [X] [command]"
    function repeat()      
    {
        local i max
        max=$1; shift;
        for ((i=1; i <= max ; i++)); do  # --> C-like syntax
            eval "$@";
        done
    }
    
    
    # Make some of the file manipulation programs verbose
    alias mv="mv -v"
    alias rm="rm -vi"
    alias cp="cp -v"
    
    # Prints disk usage in human readable form
    alias d="du -sh"
    
    # Clear the screen of your clutter
    alias c="clear"
    alias cl="clear;ls;pwd"
    
    # GREP Motifications
    alias grep="grep --color"
    alias grepp="grep -P --color"
    
    
    # Json tools (pipe unformatted to these to nicely format the JSON)
    alias json="python -m json.tool"
    alias jsonf="python -m json.tool"
    
    # Edit shortcuts for config files
    alias sshconfig="${EDITOR:-nano} ~/.ssh/config"
    alias bashrc="${EDITOR:-nano} +120 ~/.bashrc && source ~/.bashrc && echo Bash config edited and reloaded."
    
    # SSH helper
    alias sshclear="rm ~/.ssh/multiplex/* -f && echo SSH connection cache cleared;"
    alias sshlist="echo Currently open ssh connections && echo && l ~/.ssh/multiplex/"
    
    
  • although actually, the d alias looks handy

  • Love the json one. Can’t never remember the name of the library!

  • I only use one, apt to alias aptitude …

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
Submit an Answer
27 answers

The one that I always make sure to include is:

alias sudo='sudo '

This looks a bit confusing, but essentially, it makes all of the other aliases you define function correctly when used with sudo. The ALIASES section of the bash manual says:

If the last character of the alias value is a blank, then the next command word following the alias is also checked for alias expansion.

So this is just a nice way of making sure your commands are evaluated for aliases before being passed over to sudo, which ends up being pretty useful.

alias ls='ls -AlhF --color=auto'

NEVER terminal without it ;-)

edited by asb

I use fish, and with its command history and navigation, I’ve been able to skip a whole bunch of aliases.

trim off that pesky carriage return at the end of pbcopy on a mac.

alias copy="tr -d '\n' | pbcopy"

One I use all the time (but doesn’t work with hashed values in .known_hosts):

# SSH auto-completion based on entries in known_hosts.
if [[ -e ~/.ssh/known_hosts ]]; then
  complete -W "$(echo `cat ~/.ssh/known_hosts | cut -f 1 -d ' ' | sed -e s/,.*//g | uniq | grep -v "\["`;)" ssh
fi

This returns one random line from the file specified as first parameter:

function raffle() {
  head -$((${RANDOM} % `wc -l < $1` + 1)) $1 | tail -1
}

For OSX this one can be quite fun:

alias talk='cat - | while read cat; do say $cat; done'

And the most important one:

# get random BOFH excuse
function bofh() {
    telnet towel.blinkenlights.nl 666
}

Here are a few more of my favorite aliases.

Show/hide hidden files in the macOS Finder:

alias show="defaults write com.apple.finder AppleShowAllFiles -bool true && killall Finder"
alias hide="defaults write com.apple.finder AppleShowAllFiles -bool false && killall Finder"

Limit ping to five ECHO_REQUEST packets:

alias ping='ping -c 5'

Display drives and space in human readable format:

alias drives='df -h'

Run this one in ~/ to discover what folders are using the most space:

alias usage='du -h -d1'

Colorize grep output

alias grep='grep --color=auto -n'

Clear the screen (can’t live without this one!)

alias c='clear'

That’s all, folks!

  • A neat improvement to your disk usage alias is
    du -cBM -d1 2> >(grep -v 'Permission denied') | sort -n

    Personally I find I get a ton of unwanted “Permission denied” messages, so I figured I may as well hide them :)

A few docker shortcuts.

# Docker stuff
# Clean stopped containers
alias cco="docker ps -a | grep "Exited" | awk '{print $1}' | xargs docker rm"
# After that, clean unused images to reclaim disk space
alias cimg="docker images | grep none | awk '{print \$3}' | xargs docker rmi"
# Finally the regular stuff just to save typing.
alias dps="docker ps -a"
alias di="docker images"
alias drmi="docker rmi"
alias drm="docker rm"

A system notification to popup when a long shell task finishes:

# Display an "alert" after running commands.  Use like so:
#   sleep 10; alert "Done sleeping"
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
  • Some others docker commands. Could be improved.

    # Get last container id
    alias d:last="docker ps -lq"
    
    # Open a bash terminal in last Container if arguments are different than 1
    # Open a bash terminal in the container passed through argument 1 (id or name)
    d:bash () {
      if [ $# != 1 ]; then
        docker exec -it `d:last` bash
      else
        docker exec -it $1 bash
      fi
    }
    
    #With no argument runs a bash terminal in a new ubuntu container(could be specified 
    #any image) with current directory content mapped to '/app' inside container.
    #if an image is passed to the first argument this one will run.
    #if multiples arguments append to the image.
    d:run () {
      if [ $# == 0 ]; then
        docker run -it -v `pwd`:/app -w /app --rm buildpack-deps:trusty bash
      elif [ $# == 1 ]; then
        docker run -it -v `pwd`:/app -w /app --rm $1 
      else
        docker run -it -v `pwd`:/app -w /app --rm $1 ${@:2}
      fi
    }
    

For starters, I’ve got some aliases set up for common typos, e.g:

alias cd..='cd ..'
alias cd~='cd ..'

This Ubuntu default is great for sending notifications when a long running command exits:

alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

I spend a lot of time building Debin packages with pbuilder. So these come in handy:

alias sid-update="pbuilder-dist sid update; if [ -f /usr/bin/notify-send ]; then alert; fi"
alias experimental-update="pbuilder-dist experimental update; if [ -f /usr/bin/notify-send ]; then alert; fi"
alias trusty-update="pbuilder-dist trusty update; if [ -f /usr/bin/notify-send ]; then alert; fi"
alias x-update="pbuilder-dist xenial update; if [ -f /usr/bin/notify-send ]; then alert; fi"
alias y-update="pbuilder-dist xenial update; if [ -f /usr/bin/notify-send ]; then alert; fi"

function sid-build () { pbuilder-dist sid build "$@"; \ 
    if [ -f /usr/bin/notify-send ]; then alert; fi }
function experimental-build () { pbuilder-dist experimental build "$@"; \ 
    if [ -f /usr/bin/notify-send ]; then alert; fi }
function trusty-build () { pbuilder-dist trusty build "$@"; \ 
    if [ -f /usr/bin/notify-send ]; then alert; fi }
function x-build () { pbuilder-dist xenial build "$@"; \ 
    if [ -f /usr/bin/notify-send ]; then alert; fi }
function y-build () { pbuilder-dist yakkety build "$@"; \ 
    if [ -f /usr/bin/notify-send ]; then alert; fi }

There’s a could things going on there:

  • I test for the notify-send binary so I can use the same .bashrc file on my desktop or on a Droplet.
  • Bash aliases can not take arguments, so I’m also using a few functions.

Excited to see what others are using!

I am a MySQL DBA. Here are some of my most used:

alias ..="cd .."
alias ...="cd ..; cd .."
alias ll="ls -l"
alias g="grep -i"
alias csv="paste -d, -s"
alias mycon="mysql -A -h"
  • The ‘csv’ alias is used when I have a list of items that I want to change to a CSV. My most used case is a situation when I have a file that contains id’s, one per line, and I want to convert it to a MySQL IN list.

I use them for easy switching between projects, e.g.:

alias cx="cd ~/work/src/github.com/xmudrii/"
alias .x="cd ~/work/src/github.com/xmudrii/project && go install"

And starting servers:

alias api="nodemon ~/someproject-api"

Also easy ssh and vim

alias .ans="~/test/mng/ansible/"
alias ish="ssh ip"
alias dsh=dssh
alias v="vim"
alias .v=vimproject

dssh() {
    doctl compute ssh $1
}

vimproject() {
    vim ~/work/src/github.com/xmudrii/caffebar-comm/$1
}

Also this thread give me some very nice ideas, thanks for sharing! :)

  • Love the dssh function! Going to steal that one. =)

    • doctl is epic thing, helps a lot. :)
      It can be improved a lot but I’m too lazy for it now, and planning to reinstall my PC Soon™ so after that. xD
      This is also pretty good improvement, make it able to login with another user :)

      dssh() {
          if [ ! -z $2 ] 
          then 
              doctl compute ssh $1 --ssh-user $2
          else
              doctl compute ssh $1
          fi
      
      }
      

I use tmux a ton. So I have these:

alias tn='tmux new-session -s'                                # tmux new session
alias ta='tmux attach -t'                                     # tmux attach
alias tl='tmux ls'                                            # list
alias tk='tmux kill-session -s'                               # kill session name

And this for interactive terminals:

# ask for tmux but only if we're not in tmux
if [[ ! $TERM =~ screen ]]; then
  # list tmux sessions
  tmux list-sessions 2> /dev/null
  echo "want tmux?"
  read answer
  if [[ $answer == "y" ]]; then
    tmux && exit 0
  fi
fi

And since I tweak my configuration a lot, I have aliases for those:

alias ep='vim ~/.bash_profile'                                # edit bash_profile
alias ev='vim ~/.vim/vimrc_main'                              # edit shared vim conf
alias evv='vim ~/.vim/vundle'                                 # edit vim plugins
alias evp='vim ~/.vim/vimrc_private'                          # edit private vim settings
alias et='vim ~/.tmux.conf'                                   # edit tmux conf
Previous 1 2 3 Next