Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Is there anything that you can't live without and will make my life SO much easier? Here are some that I use ('diskspace' & 'folders' are particularly handy).

# some more ls aliases
alias ll='ls -alh'
alias la='ls -A'
alias l='ls -CFlh'
alias woo='fortune'
alias lsd="ls -alF | grep /$"

# This is GOLD for finding out what is taking so much space on your drives!
alias diskspace="du -S | sort -n -r |more"

# Command line mplayer movie watching for the win.
alias mp="mplayer -fs"

# Show me the size (sorted) of only the folders in this directory
alias folders="find . -maxdepth 1 -type d -print | xargs du -sk | sort -rn"

# This will keep you sane when you're about to smash the keyboard again.
alias frak="fortune"

# This is where you put your hand rolled scripts (remember to chmod them)
PATH="$HOME/bin:$PATH"
share

locked by HopelessN00b Dec 3 at 1:31

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

closed as not constructive by RobM, EEAA, Scott Pack, HopelessN00b, mdpc Oct 31 '12 at 16:50

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

3  
This should be community wiki –  Toro May 6 '09 at 14:53
1  
Turned into community wiki. Enjoy. –  gyaresu May 6 '09 at 22:50
4  
piped to more? I bet you'd be happier with less or less -F –  derobert May 7 '09 at 16:28
1  
Just in case anyone is interested, there is a service that allows you to browse, build a list and source your aliases: alias.sh –  Sam152 Apr 22 '13 at 0:13

39 Answers 39

up vote 82 down vote accepted

I have a little script that extracts archives, I found it somewhere on the net:

extract () {
   if [ -f $1 ] ; then
       case $1 in
           *.tar.bz2)   tar xvjf $1    ;;
           *.tar.gz)    tar xvzf $1    ;;
           *.bz2)       bunzip2 $1     ;;
           *.rar)       unrar x $1       ;;
           *.gz)        gunzip $1      ;;
           *.tar)       tar xvf $1     ;;
           *.tbz2)      tar xvjf $1    ;;
           *.tgz)       tar xvzf $1    ;;
           *.zip)       unzip $1       ;;
           *.Z)         uncompress $1  ;;
           *.7z)        7z x $1        ;;
           *)           echo "don't know how to extract '$1'..." ;;
       esac
   else
       echo "'$1' is not a valid file!"
   fi
 }
share
1  
Nice. Again though, there's that IDE/Vim argument regarding know the commands from memory. Fantastic bit of script though. Definitely going in the .bashrc Cheers! –  gyaresu May 5 '09 at 1:07
19  
There's a nice and simple linux command called "unp", the Unpacker that does this and more. –  Sander Marechal May 10 '09 at 23:33
7  
Newer versions of tar detect automatically the archive type, so can extract all supported formats by just 'tar xvf'. –  Prof. Moriarty Jun 8 '10 at 17:47

I deal with a lot of different machines so one of my favorites is aliases for each machine that I need to frequently SSH to:

alias claudius="ssh dinomite@claudius"

It is also useful to setup a good .ssh/config and ssh keys to make hopping amongst machines even easier.

Another one of my favorite aliases is for moving up directories:

alias ..="cd .."
alias ...="cd ../.."
alias ....="cd ../../.."
alias .....="cd ../../../.."

And some for commonly used variations of ls (and typos):

alias ll="ls -l"
alias lo="ls -o"
alias lh="ls -lh"
alias la="ls -la"
alias sl="ls"
alias l="ls"
alias s="ls"

History can be very useful, but by default on most distributions your history is blown away by each shell exiting, and it doesn't hold much to begin with. I like to have 10,000 lines of history:

export HISTFILESIZE=20000
export HISTSIZE=10000
shopt -s histappend
# Combine multiline commands into one in history
shopt -s cmdhist
# Ignore duplicates, ls without options and builtin commands
HISTCONTROL=ignoredups
export HISTIGNORE="&:ls:[bf]g:exit"

That way, if I know that I've done something before but can't remember the specifics, a quick history | grep foo will help jog my memory.

I often found myself piping output through awk in order to get a certain column of the output, as in df -h | awk '{print $2}' to find the size of each of my disks. To make this easier, I created a function fawk in my .bashrc:

function fawk {
    first="awk '{print "
    last="}'"
    cmd="${first}\$${1}${last}"
    eval $cmd
}

I can now run df -h|fawk 2 which saves a good bit of typing.

If you need to specify a delimiter (e.g., awk -F: for /etc/passwd), this function obviously can't handle that. The slightly-overhauled version in this gist can handle arbitrary awk arguments before the field number (but still requires input from stdin).

share
2  
I use the ssh alias and ssh keys too... it makes every so easy –  devin May 30 '09 at 15:14
1  
+1 for the history control tips. –  Rene Saarsoo Jun 25 '09 at 22:39
2  
you can put hostname aliases in .ssh/config to the same effect. In this case, add an entry 'Host cloudius' with 'username dinomite' –  Sirex Oct 30 '12 at 23:16
mkdircd () { mkdir -p "$@" && eval cd "\"\$$#\""; }

ecb () { emacsclient -n -a emacs $@ & } # open in emacsclient in the background
ecp () { emacsclient -n $(which $@) & } # open a given file found in a $PATH in emacsclient
ecr () { SUDO_EDITOR="emacsclient -a emacs" sudoedit $@; } # start emacsclient or emacs and open the file as root

eCf () { emacs --batch --eval "(byte-compile-file \"$@\")"; } # byte-compile file
eCa () { emacs --batch --eval "(batch-byte-compile-if-not-done)" *.el; } # byte-compile all el files in the current directory and it's children
share

I used to set these up all over the place but then realized that it was better to just remember how to do them 'manually' because it meant I would 1) fully understand what was going on and 2) have access to these capabilities even if my custom .bashrc wasn't installed.

The only thing I use aliases for these days are to cut down on repetitive typing of really long lines (eg. alias myhost='ssh -T user@my.remote.host screen -dAr' )

share
2  
Agreed regarding memorising long useful commands. I find though that I'm running 'diskspace' fairly often on runaway servers (i.e. php is coredumping all over the place). –  gyaresu May 4 '09 at 1:24
1  
It's easy enough to deploy your custom configuration on systems you regularly use, though. –  Tobu Nov 15 '10 at 17:59

GPG encrypted bashrc

I'm sure we all have things we'd like to put in our bashrc that we don't want easily readable by sudoers. My solution to this is:

if [ -f ~/.bash_private.gpg ]; then
   eval "$(gpg --decrypt ~/.bash_private.gpg 2>/dev/null)"
fi

I have a GPG agent that makes it so I only have to enter my private key's password once every few hours. You still have to have some trust in the users of the system because your variable, functions, and aliases that you define could be extracted from RAM. However, I use this mainly for my laptop. If it gets stolen, I don't want someone easily seeing things like:

alias MYsql='mysql -uadmin -psecret'
wglatest(){ wget -O https://admin:secret@server.com/latest; }
share

Color for manpages in less makes manpages a little easier to read:

export LESS_TERMCAP_mb=$'\E[01;31m'
export LESS_TERMCAP_md=$'\E[01;31m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[01;44;33m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[01;32m'

Colored manpages can also be obtained by installing most and using it as MANPAGER env variable. If you want to use this pager not only for man, use the PAGER variable, like this:

export PAGER="/usr/bin/most -s"
share

From Automating Linux and Unix Administration by Kirk Bauer (great book!)

PS1='\n[\u@\h]: \w\n$?> '

The newline at the beginning is mine, I like to have a clear line between the previous output and the prompt. The rest is:

\u = username

\h = host

\w = working directory

$? = last return code

share
# vi ~/.bashrc # red/green terminal colors regarding exit code
export PROMPT_COMMAND='PS1="`
if [[ \$? = "0" ]];
then echo "\\[\\033[0;32m\\]";
else echo "\\[\\033[0;31m\\]";
fi`[\u@\h \w]\[\e[m\] "'
export PS1
share
IP_ADDRESS_BASH=`ip addr | grep -w inet | gawk '{if (NR==2) {$0=$2; gsub(/\//," "); print $1;}}'`
PS1="\h $IP_ADDRESS_BASH \w % "

And then it displays IP of your machine that you just logged to.

share

A couple good ones

Make SSH automatically complete the hostname you ssh to (if it's in your config or history)

complete -o default -o nospace -W "$(/usr/bin/env ruby -ne 'puts $_.split(/[,\s]+/)[1..-1].reject{|host| host.match(/\*|\?/)} if $_.match(/^\s*Host\s+/);' < $HOME/.ssh/config)" scp sftp ssh

Some useful bash completion settings

bind "set completion-ignore-case on" # note: bind used instead of sticking these in .inputrc
bind "set bell-style none" # no bell
bind "set show-all-if-ambiguous On" # show list automatically, without double tab

Some useful ones for Mac OS X

alias nospotlight='sudo mdutil -a -i off'
alias cleardnscache='sudo killall -HUP mDNSResponder'
alias ldd='otool -L'
alias seq='jot - '
alias eject='drutil eject'
share

The 'folders' alias is great! I modified it slightly so that directories with spaces don't cause errors.

alias folders='find . -maxdepth 1 -type d -print0 | xargs -0 du -sk | sort -rn'
share
2  
folders sorted by disk usage, nice –  dotjoe Jul 8 '10 at 21:50

Here are mines:

export HISTCONTROL=ignoredups
export HISTIGNORE="&:ls:bg:fg"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# shows you if you are in a chroot or in a git repository
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;30m\]\h\[\033[00m\]:\[\033[01;34m\]\W\[\033[00m\]$(__git_ps1)\$ '


if [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
fi

# two handy single-letter aliases

alias u='ls -hltr'
alias e='du * -cs | sort -nr | head'
alias g='grep -C5 --color=auto'

# creates a temp dir and cds into it
alias td='pushd $(mktemp -d)'

# find <dir> <file name regexp> <file contents regexp>
function fing { find "$1" -name "$2" -exec grep -H "$3" "{}" \; }

# shows "git diff" across any project in any subdirectory
alias git-differ='for g in $(find . -name ".git"); do g=${g%%.git};printf "$g\t\t\t";pu $g >/dev/null && git diff |wc -l; p >/dev/null; done'

# does git house keeping across any project in any subdirectory
alias git-housekeep='for g in $(find . -name ".git"); do g=${g%%.git};echo $g;pu $g && git repack && git gc --auto && p;done'

# Debian update
alias apg='aptitude update && aptitude dist-upgrade && aptitude clean'

# Quick way to serve files in HTTP from the local dir
alias webs='python -m SimpleHTTPServer'
share

I use this about 20 times a day to cd into the last changed directory:

cl()
{
        last_dir="$(ls -Frt | grep '/$' | tail -n1)"
        if [ -d "$last_dir" ]; then
                cd "$last_dir"
        fi
}

These two keep permanent bookmarks of often used directories:

rd(){
    pwd > "$HOME/.lastdir_$1"
}

crd(){
        lastdir="$(cat "$HOME/.lastdir_$1")">/dev/null 2>&1
        if [ -d "$lastdir" ]; then
                cd "$lastdir"
        else
                echo "no existing directory stored in buffer $1">&2
        fi
}
share

Fedora

alias install=sudo yum install

Debian

alias install=sudo apt-get update && sudo apt-get install
share

No more cd ../../../.. but up 4

Goes up many dirs as the number passed as argument, if none goes up by 1 by default (found in a link in a comment in stackoverflow.com and modified a bit)

up(){
  local d=""
  limit=$1
  for ((i=1 ; i <= limit ; i++))
    do
      d=$d/..
    done
  d=$(echo $d | sed 's/^\///')
  if [ -z "$d" ]; then
    d=..
  fi
  cd $d
}
share

Here are a few of my favorites:

alias ls='ls -F --color=auto'
alias l='ls'
alias ll='ls -ahl'
alias ..='cd ..'
alias ...='cd ../..'
alias mv='mv -i'

mkcd() {
        if [ $# != 1 ]; then
                echo "Usage: mkcd <dir>"
        else
                mkdir -p $1 && cd $1
        fi
}

# Git related
alias gs='git status'
alias gc='git commit'
alias ga='git add'
alias gd='git diff'
alias gb='git branch'
alias gl='git log'
alias gsb='git show-branch'
alias gco='git checkout'
alias gg='git grep'
alias gk='gitk --all'
alias gr='git rebase'
alias gri='git rebase --interactive'
alias gcp='git cherry-pick'
alias grm='git rm'
share

Tail all logs in /var/log

alias logs="find /var/log -type f -exec file {} \; | grep 'text' | cut -d' ' -f1 | sed -e's/:$//g' | grep -v '[0-9]$' | xargs tail -f"
share

This is one of my favorites:

alias ssh='if [ "$(ssh-add -l)" = "The agent has no identities." ]; then ssh-add; fi; /usr/bin/ssh "$@"'

If i've forgotten to authenticate, it lets me do so without having to waste my typing doing ssh-add after the ssh session.

share

I have the following in my bashrc

function __setprompt {
  local BLUE="\[\033[0;34m\]"
  local NO_COLOUR="\[\033[0m\]"
  local SSH_IP=`echo $SSH_CLIENT | awk '{ print $1 }'`
  local SSH2_IP=`echo $SSH2_CLIENT | awk '{ print $1 }'`
  if [ $SSH2_IP ] || [ $SSH_IP ] ; then
    local SSH_FLAG="@\h"
  fi
  PS1="$BLUE[\$(date +%H:%M)][\u$SSH_FLAG:\w]\\$ $NO_COLOUR"
  PS2="$BLUE>$NO_COLOUR "
  PS4='$BLUE+$NO_COLOUR '
}
__setprompt

On a local machine it looks like:

[17:57][user:~]$

but on a remote (through ssh) it is:

[17:57][user@machine:~]$
share

I'm addicted to screen, and I use the following shortcuts for SSHing to machines. With this script, I type p hostname to SSH to a host and run screen, or o hostname to do the same but run screen on the local machine.

First a script that connects to an SSH server of the same name as the script you're running. I call this simple_ssh:

#!/bin/sh
BASENAME=$(basename $0)

if [ "$SCREEN" = "1" ]; then
	export SCREEN=0
	exec screen -RD scr$BASENAME -s $0
elif [ "$SCREEN" = "2" ]; then
	exec ssh $BASENAME "$@" -t 'screen -RD'
fi

exec ssh $BASENAME "$@"

Symlink this to mars in your path and mars becomes a shortcut for ssh mars:

adam@pluto:bin$ ln -s simple_ssh mars
adam@pluto:bin$ mars
adam@mars:~$

The $SCREEN environment variable lets you automatically execute GNU screen with the connection. SCREEN=1 runs screen locally (say, if screen is not installed on the host) and SCREEN=2 runs it on the host itself.

Use a couple aliases to shortcut this:

alias o='SCREEN=1 exec'
alias p='SCREEN=2 exec'

Use a script to create symlinks for all your hosts given an ~/.ssh/config file like this:

Host mars
    HostName mars.example.com
    User abackstrom

The script, sshconfig2simplessh:

#!/bin/sh

BASENAME=$(basename "$0")
USAGE="Usage: $BASENAME /path/to/bin"

if [ -z "$1" ] ; then
	echo $USAGE
	exit 0
fi

if [ ! -d "$1" ] ; then
	echo "$1 is not a directory" >&2
	exit 1
fi

cd "$1"

HOSTS=$(grep '^Host ' < ~/.ssh/config | cut -d' ' -f2)

for HOST in $HOSTS ; do
	if [ ! -e "$HOST" ]; then
		echo ln -s simple_ssh "$HOST"
		ln -s simple_ssh "$HOST"
	fi
done
share

To fix window size in GNU screen after resize:

shopt -s checkwinsize

To show the permissions on a directory, shortcut ls -ld:

alias lld='ls -ld'

History viewing:

alias h='history | zgrep'

And contents of my zgrep script, which I couldn't figure out how to cram directly into the alias:

#!/bin/sh
grep "${*-.}"
share

A few aliases I use to take the edge off of the daily CLI grind...

# I find myself doing this a lot
alias hg='history | grep '

# Likewise this, plus I'm always mistyping it...
alias findy='find . -name'

# sometimes you're just not sure you want to delete something...
alias trash='mv -t ~/.local/share/Trash/files --backup=t'

alias vb='vim ~/.bashrc'

# I find typing 'cd ..' less than optimal
alias up='cd ..'
alias 2up='cd ../../'
alias 3up='cd ../../../'
alias 4up='cd ../../../../'

# re-map caps lock key to be Ctrl
# (works on Linux, at least)
xmodmap -e "remove lock = Caps_Lock"
xmodmap -e "add control = Caps_Lock"

# helpful history settings:
export HISTCONTROL=ignoredups
export HISTCONTROL=ignoreboth
export HISTIGNORE=ls:ll:la:l:cd:pwd:exit:mc:su:df:clear:cls
share

. $HOME/bin/git-prompt/git-prompt.sh

share

I use my bashrc on numerous machines, so i've got this little snippet to make sure LS is colourized. This will fix it on OSX machines, maybe even *BSD if you adjust the uname line.

if [ "$TERM" != "dumb" ]; then
    if [ `uname` == "Darwin" ]; then
       alias ls='ls -G'
    else
       eval "`dircolors -b`"
       alias ls='ls --color=auto'
    fi
fi

Also, I've got a command to backup a file, useful if your about to change a config file and want to make a quick copy before hand.

bu () { cp $1 ~/.backup/`basename $1`-`date +%Y%m%d%H%M`.backup ; }
share

Have bash check to see if the window size has changed (prevents line-editing from going weird if you resize your terminal window)

shopt -s checkwinsize

This is my favourite. Causes bash to append to history instead of overwriting it. Typically when you launch bash, it loads history into memory, and when you close it it writes it out. This means that if you load two shells, use both, then close both, the one you closed last overwrites all changes.

This snippet causes it to first of all only append changes (instead of overwriting with the whole buffer), and then to cause it to, after every command, write out changes. In effect, you get a live updating .bash_history, so if you start a new terminal, you have all the commands from your other running sessions' history.

shopt -s histappend
PROMPT_COMMAND='history -a'
share

A little tip for Bash if you are a sysadmin and work with root privileges a lot:

shopt -o noclobber

This will prevent you from accidentally destroying the content of an already existing file if you redirect output (>filename). You can always force overwriting with >|filename.

share

To have colors for All grep commands such as grep, egrep and zgrep, I have the following in my .bashrc

export GREP_OPTIONS='--color=auto'
share

I sometimes have to use a Solaris system at work.

However the system is centrally managed via Puppet, including the password file (which includes the shell setting).

My .bashrc therefore reads something like:

%!/bin/bash
exec /bin/tcsh

:)

share

The one liners and tiny scripts out there could go on forever. I recommend man bash and writing things yourself. Some good short bash stuff at http://www.commandlinefu.com. Heres a few things.

#use extra globing features. See man bash, search extglob.
shopt -s extglob
#include .files when globbing.
shopt -s dotglob
#When a glob expands to nothing, make it an empty string instead of the literal characters.
shopt -s nullglob
# fix spelling errors for cd, only in interactive shell
shopt -s cdspell
# vi mode
set -o vi

s() { # do sudo, or sudo the last command if no argument given
    if [[ $# == 0 ]]; then
    	sudo $(history -p '!!')
    else
    	sudo "$@"
    fi
}

prompt_command() {
    p=$PWD  # p is much easier to type in interactive shells
    # a special IFS should be limited to 1 liners or inside scripts.
    # Otherwise it only causes mistakes.
    unset IFS
}
PROMPT_COMMAND=prompt_command


# smart advanced completion, download from
# http://bash-completion.alioth.debian.org/
if [[ -f $HOME/local/bin/bash_completion ]]; then
    . $HOME/local/bin/bash_completion
fi


extract () { # extract files. Ignore files with improper extensions.
    local x
    ee() { # echo and execute
    	echo "$@"
    	$1 "$2"
    }
    for x in "$@"; do
    	[[ -f $x ]] || continue
    	case "$x" in
    		*.tar.bz2 | *.tbz2 )	ee "tar xvjf" "$x"	;;
    		*.tar.gz | *.tgz ) ee "tar xvzf" "$x"	;;
    		*.bz2 )				ee "bunzip2" "$x"	;;
    		*.rar )				ee "unrar x" "$x"   ;;
    		*.gz )				ee "gunzip" "$x"    ;;
    		*.tar )				ee "tar xvf" "$x"   ;;
    		*.zip )				ee "unzip" "$x"     ;;
    		*.Z )				ee "uncompress" "$x" ;;
    		*.7z )				ee "7z x" "$x"      ;;
    	esac
    done
}
share
2  
I like your history -p trick. –  Tobu Jul 2 '10 at 10:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.