Take the 2-minute tour ×
Server Fault is a question and answer site for professional 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|improve this question

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|improve this answer
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

Since I use so many different machines, my .bashrc always sets the command prompt to include, among other things, the name of the server I am currently logged into. This way, when I am three levels deep in telnet/ssh, I don't type the wrong thing in the wrong window. It really sucks to rm -rf . in the wrong window! (Note: At home, telnet is disabled on all machines. At work, ssh is not always enabled and I don't have root access to very many machines.)

I have a script ~/bin/setprompt that is executed by my .bashrc, which contains:

RESET="\[\017\]"
NORMAL="\[\033[0m\]"
RED="\[\033[31;1m\]"
YELLOW="\[\033[33;1m\]"
WHITE="\[\033[37;1m\]"
SMILEY="${WHITE}:)${NORMAL}"
FROWNY="${RED}:(${NORMAL}"
SELECT="if [ \$? = 0 ]; then echo \"${SMILEY}\"; else echo \"${FROWNY}\"; fi"

# Throw it all together 
PS1="${RESET}${YELLOW}\h${NORMAL} \`${SELECT}\` ${YELLOW}>${NORMAL} "

This script sets the prompt to the host name followed by :) if the last command was successful and :( if the last command failed.

share|improve this answer
6  
I also show the status in my prompt, but keep the numeric value and colour it red if non-zero, otherwise green. –  pgs Jun 1 '09 at 10:01

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|improve this answer

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|improve this answer

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.

share|improve this answer
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

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|improve this answer

this is an awesome resource for this:

show us your .bashrc

share|improve this answer

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|improve this answer
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

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|improve this answer
2  
I like your history -p trick. –  Tobu Jul 2 '10 at 10:50

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|improve this answer

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|improve this answer

I've had this in my .bashrc for a while and I've found it helpful. If you are sshing in to the box, is starts screen automatically when you login, that way when your network connection gets interrupted or whatever, you don't lose whatever you were doing. It should be placed at the end.

if [ "$PS1" != "" -a "${STARTED_SCREEN:-x}" = x  -a "${SSH_TTY:-x}" != x ]
then
STARTED_SCREEN=1 ; export STARTED_SCREEN
[ -d $HOME/lib/screen-logs ] || mkdir -p $HOME/lib/screen-logs

sleep 1
screen -U -RR && exit 0

echo "Screen failed! continuing with normal bash startup"
fi
share|improve this answer

How many aliases to fortune do you need, anyway?

I like to make a cdd alias that takes me to wherever I'm presently most likely to be working on that server.

PATH redefinition really belongs in .bash_profile, not .bashrc.

On a server where I routinely use a large set of screens, my .bashrc will have:

alias s1="screen -dr chaos1"
alias s2="screen -dr chaos2"
alias s3="screen -dr chaos3"
# ... and so on

(The screens were set up with, for example, screen -U -S chaos1.)

share|improve this answer
2  
@chaos "How many aliases to fortune do you need, anyway?". woo for win. frak(and alternate spellings) for fail. –  gyaresu May 4 '09 at 0:56
3  
@Ian Kelling: What I'm actually saying is that operations that should be performed once per login belong in .bash_profile and operations that should be performed once per shell instantiation belong in .bashrc. –  chaos May 4 '09 at 11:43

Among other things, I set some defaults for less, prevent accidentally closing my terminal and enable forward navigation through history:

# ignore case, long prompt, exit if it fits on one screen, allow colors for ls and grep colors
export LESS="-iMFXR"

# must press ctrl-D 2+1 times to exit shell
export IGNOREEOF="2"

# allow ctrl-S for history navigation (with ctrl-R)
stty -ixon
share|improve this answer

I have a few bits:

# stop the pc speaker ever annoying me :)
setterm -bfreq 0

# don't put duplicate lines in the history. See bash(1) for more options
HISTCONTROL=ignoredups
# ... and ignore same sucessive entries.
HISTCONTROL=ignoreboth

# Expand the history size
HISTFILESIZE=10000 
HISTSIZE=100

# commands with leading space do not get added to history
HISTCONTROL=ignorespace

# am I on the internet?
alias p4='ping 4.2.2.2 -c 4'

# pwsafe
alias pw='pwsafe -p'

# ls aliases
alias ll='ls -l'
alias la='ls -A'
alias l='ls -CF'
alias lt='ls -laptr' #oldest first sort
alias labc='ls -lap' #alphabetical sort

# cd aliases
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'

# cd into the old directory
alias bd='cd "$OLDPWD"'

# install a package and automatically respond yes to confirmation prompt
alias ins="sudo aptitude install"

# remove a package and its configuration files
alias remp="sudo aptitude purge"

# search for a package - apt-cache and aptitude search in different ways
# so have both
alias searchc="apt-cache search"
alias search="aptitude search"
alias show="aptitude show"
share|improve this answer
3  
Your HISTCONTROL lines override each other, since it's just a shell variable. ignoreboth combines ignorespace and ignoredups. –  Adam Backstrom May 27 '09 at 14:34
4  
Try cd - instead of bd –  ptman Jul 2 '10 at 9:15

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|improve this answer

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|improve this answer

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|improve this answer
2  
folders sorted by disk usage, nice –  dotjoe Jul 8 '10 at 21:50

I would echo @pjz's comment about knowing things manually rather than setting them up. Especially if you access numerous machines, like I always seem to do.

So one I definitely know is set -o vi because I know the vi-editing commands in bash and I don't know the emacs ones (besides, Ctrl+A interferes with screen). On my own boxes, I put that in .bashrc

I also find I have to include export EDITOR=vim because a number of recent distros default to nano which is most annoying to be thrown into by a utility that needs you to edit something, when I was expecting vi. :-/

I also alter my prompt. I found a long long time ago that adding the last error code is just useful enough that I like it. And I like the full pathname in the prompt. And the current screen number, too. And it just makes sense to include the current user and hostname. My prompt is PS1='\u@\h $PWD $WINDOW [$?] \$ '

share|improve this answer

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|improve this answer

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|improve this answer

These are my favorites:

export HISTFILESIZE=1000000000
export HISTSIZE=1000000

I like having a command-line history that never forgets.

Unfortunately, awhile back I launched a shell from cron which didn't read .bashrc somehow, and chopped everything down to 500 lines, destroying over a years' history. So I recommend these go in /etc/bashrc.

share|improve this answer

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|improve this answer

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|improve this answer

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|improve this answer

I compile a number of things manually into $HOME/local so I have this little snippet:

for prog in $HOME/local/*
do
    if [ -d "$prog/bin" ]; then
        export PATH=$prog/bin:$PATH
    fi
    if [ -d "$prog/include" ]; then
        export C_INCLUDE_PATH=$prog/include:$C_INCLUDE_PATH
    fi
    if [ -d "$prog/lib" ]; then
        export LD_LIBRARY_PATH=$prog/lib:$LD_LIBRARY_PATH
        export LIBRARY_PATH=$prog/lib:$LIBRARY_PATH
    fi
    if [ -d "$prog/man" ]; then
        export MANPATH=$prog/man:$MANPATH
    fi
    if [ -d "$prog/share/man" ]; then
        export MANPATH=$prog/share/man:$MANPATH
    fi
done

I also have my IRC client on my server running in screen so I have this (not a .bashrc thing, but still useful)

#!/usr/bin/env bash

RUNNING=`screen -ls | grep irc`
if [ "" = "$RUNNING" ]; then
   screen -S irc irssi
else
   screen -dr irc
fi
share|improve this answer

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|improve this answer

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|improve this answer

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|improve this answer

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