asb
By:
asb

What are your favorite bash aliases?

September 2, 2016 15.5k 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?

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 ...

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 :)

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

Not my favorite, but definitely what I use more:

alias :q='exit'

Vim++

Quickly reload .bash_profile to enable changes.

alias reload='source .bash_profile'

Search for running processes.

alias psg='ps -ef | grep '

Example: psg BBEdit

Check for Homebrew updates, brew upgrades, and then cleanup.

alias update='brew update && brew upgrade --all && brew cask update && brew cleanup && brew cask cleanup'

Recursively delete those annoying .DS_Store files.

alias cleanup="find . -type f -name '*.DS_Store' -ls -delete"

Extract the contents of a .tar file.

alias untar='tar -xvf'

Print out the local IP on en0.

alias iplocal='ifconfig en0 | grep --word-regexp inet | awk "{print $2}"'

Print out the public ip address.

alias ippub="dig +short myip.opendns.com @resolver1.opendns.com"

Generate a random 20 character password using OpenSSL.

alias randpass="openssl rand -base64 20"
  • you may want to check out pwgen for password generation. It gives you a lot of options (charset, length, number of passwords, accommodating silly website policies (at least one capital/number/symbol, etc)), and avoids the pesky trailing =

    • I checked out pwgen and it's great. I just wish I could tell it to output something other than eight character passwords. Thanks for the comment! :-)

      • check out pwgen --help, it shows how to change the length. For example, pwgen 20 will print out 20 char passwords. My 2 main issues are that by default it prints out a list of passwords instead of just one (you can specify with eg pwgen 20 1), and that by default it weights certain letter combinations for "memorability", which I don't think is a good default (you can turn that off with eg pwgen -s 20 1 for one completely random 20 char password).

        I first found out about pwgen through pass, a really great password manager that uses pwgen to generate passwords.

        However, the best password generator I know of is secpwgen, which I typically don't recommend people because it's not in most distros' repos and its build process is a little different.

Ha ha I have this one:

alias PANIC="espeak 'OH NO, the sky is falling'"

Everyone in the office just rolls their eyes

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
    }
    

A docker and git alias, mainly because I can't type and my typos are actually quite comical in terms of their use/misuse.

alias dicker='docker'
alias goit='git'

Keep all your bash history:

export HISTTIMEFORMAT="%s "
PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND ; }"'echo $$ $USER \
               "$(history 1)" >> ~/.bash_eternal_history'

extract files:

extract () {
  if [ -f $1 ] ; then
    case $1 in
      *.tar.bz2)  tar xjf $1    ;;
      *.tar.gz) tar xzf $1    ;;
      *.bz2)    bunzip2 $1    ;;
      *.rar)    rar x $1    ;;
      *.gz)   gunzip $1   ;;
      *.tar)    tar xf $1   ;;
      *.tbz2)   tar xjf $1    ;;
      *.tgz)    tar xzf $1    ;;
      *.zip)    unzip $1    ;;
      *.Z)    uncompress $1 ;;
      *)      echo "'$1' cannot be extracted via extract()" ;;
    esac
  else
    echo "'$1' is not a valid file"
  fi
}

Complete hosts:

_complete_hosts () {
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    host_list=`{
        for c in /etc/ssh_config /etc/ssh/ssh_config ~/.ssh/config
        do [ -r $c ] && sed -n -e 's/^Host[[:space:]]//p' -e 's/^[[:space:]]*HostName[[:space:]]//p' $c
        done
        for k in /etc/ssh_known_hosts /etc/ssh/ssh_known_hosts ~/.ssh/known_hosts
        do [ -r $k ] && egrep -v '^[#\[]' $k|cut -f 1 -d ' '|sed -e 's/[,:].*//g'
        done
        sed -n -e 's/^[0-9][0-9\.]*//p' /etc/hosts; }|tr ' ' '\n'|grep -v '*'`
    COMPREPLY=( $(compgen -W "${host_list}" -- $cur))
    return 0
}
complete -F _complete_hosts ssh
complete -F _complete_hosts sshs
complete -F _complete_hosts host
complete -F _complete_hosts telnet
complete -F _complete_hosts ping

Complete lxc/lxd containers: (~/etc/containers must be created first)

_complete_container () {
    lxc list|grep PERSIS | awk '{print $2}'|sort|uniq >| /home/$USER/etc/containers
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    host_list=`{
        for k in /home/jonathan/etc/containers
        do [ -r $k ] && egrep -v '^[#\[]' $k|cut -f 1 -d ' '|sed -e 's/[,:].*//g'
        done
        sed -n -e 's/^[0-9][0-9\.]*//p' /home/jonathan/etc/containers; }|tr ' ' '\n'|grep -v '*'`
    COMPREPLY=( $(compgen -W "${host_list}" -- $cur))
    return 0
}
complete -F _complete_container c

c() {
        lxc exec $1 -- /bin/bash
}

proxy remote:

proxy_src_remote () {
 ssh $1@$2 -R 3128:localhost:3128
}
edited by asb

In last few months I started using ZSH + http://ohmyz.sh/ as my default shell and it's AWESOME!

My favorite alias/function:

randompw()
{
    cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w ${1:-32} | head -n 1
}

Some of my favorites:

Merges current branch into master then git checkout back to develop

alias mergemaster='git checkout master; git pull; git merge develop; git push; git checkout develop'

Adds everything from current folder to git

alias add='git add .'

For Node developers:

alias s='npm start'
alias lint='npm run lint'

Docker:

alias dockerstop='docker-compose stop'
alias dockerup='docker-compose up -d'
alias dockerrm='docker-compose rm --all'

One I must have when I use Sublime Text

alias slt='subl'

When I do presentations on my Mac I like to hide the mess on my desktop.

alias hideDesktop='defaults write com.apple.finder CreateDesktop -bool false; killall Finder;'
alias showDesktop='defaults write com.apple.finder CreateDesktop -bool true; killall Finder;'

Start my screensaver

alias afk="open /System/Library/Frameworks/ScreenSaver.framework/Versions/A/Resources/ScreenSaverEngine.app"

Send my Mac to sleep:

alias sleep="pmset sleep now"

List global installed packages and bottles.

alias npml='npm list -g --depth=0'
alias brewl='brew leaves'

My favorite

alias fuck='sudo !!'

Some functions inside my .zshrc

function clock() {
    watch -t -n1 "echo "" && date +""$'  '"%T""
}
function c() {
    clear; cd $1; l;
}

(for mac users)

# Change directory to the current Finder directory
function cdf() {
    target=`osascript -e 'tell application "Finder" to if (count of Finder windows) > 0 then get POSIX path of (target of front Finder window as text)'`
    if [ "$target" != "" ]; then
        cd "$target"; pwd
    else
        echo 'No Finder window found' >&2
    fi
}

alias myips="ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p'"
shows a listing of your IP addresses, works great if you have multiple /dev/eth* (OSX/nix)

Technically not an alias, but you could probably make it work as one,

Get the price of Monero (XMR) !

function mon () {
  curl -s --url "https://www.coingecko.com/en/price_charts/monero/usd" | grep "value of Monero for today is" | cut -d '>' -f 2 | cut -d '<' -f 1
}

I get a bit desperate when trying to parse logs without my rank alias. It answers the question "what is the most common line in this stream"

alias rank="sort| uniq -c|sort -n"

Tired of mkdir bla; cd bla

mkcd() { mkdir $1;cd $1; }

Clean up exploded tarballs:

mkmvcd() { mkdir ${*: -1:1}; mv $*; cd ${*: -1:1}; }

tar -vxzf bad.tgz
oh curses..
mkmvcd readme.md badsubfolder bad* baddir

Because i write way to many shell scripts:

alias cx="chmod +x"

Run make from a sub-directory of a project.

mk (){
        if [ $PWD == "/" ]; then
                echo "FAILED :("
        elif [ ! -f Makefile ]; then
                pushd .. > /dev/null
                mk $*
                popd > /dev/null
        else 
                pwd
                echo make $*
                make $*
        fi
}

Try to do something and give it 3 attempts for it to work (ideal for backup scripts etc when you don't want to be woken up or turn up to work the following morning to a failed job)

try_thrice() { $@ || $@ || $@ }

add datestamp to the beginning of each line of a log

log() {
case $# in
0) CMD="cat -";;
*) CMD="echo $@";;
esac
$CMD | while read line ; do
echo `date '+%Y-%m-%d %H:%M:%S'` $line
done | tee -a $LOGFILE
}

ala:-

$ do_something | log

or

$ log "something happened"

Hi Melissa,

I am unable to run the MapReduce hadoop-mapreduce-examples with different name instead of 'Principal [.]*'

alias fucking='sudo'

You see when I get mad after being told I need to run as root I just type fucking 'commandnamehere'

autojump has been my most productive alias
alias z=autojump

Have another answer? Share your knowledge.