What useful things can one add to one's .bashrc?

140,877

Solution 1

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
 }

Solution 2

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.

Solution 3

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"

Solution 4

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
}

Solution 5

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:
140,877

Related videos on Youtube

Gareth
Author by

Gareth

There is no excellent beauty that hath not some strangeness in the proportion. - Sir Francis Bacon (1561 - 1626)

Updated on September 17, 2022

Comments

  • Gareth
    Gareth almost 2 years

    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"
    
    • Toro
      Toro about 15 years
      This should be community wiki
    • Gareth
      Gareth about 15 years
      Turned into community wiki. Enjoy.
    • derobert
      derobert about 15 years
      piped to more? I bet you'd be happier with less or less -F
    • GreenKiwi
      GreenKiwi about 15 years
      Except that there is that "sort" before the more, since sort needs the full input, the less -F would just let you see the sorting faster, and I bet it's pretty dang fast.
    • fmccardoso
      fmccardoso almost 15 years
      LOL, love the ' alias frak="fortune" ' line, I'll remember that one when S#!T hits the fan
    • SergioAraujo
      SergioAraujo over 12 years
      show path alias path='echo -e ${PATH//:/\\n}'
    • F. Hauri
      F. Hauri almost 11 years
      That's a nice thread, but for superuser.com
  • Gareth
    Gareth about 15 years
    @chaos "How many aliases to fortune do you need, anyway?". woo for win. frak(and alternate spellings) for fail.
  • Gareth
    Gareth about 15 years
    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).
  • pjz
    pjz about 15 years
    yeah, I actually have something similar to that (du /home/* --max-depth 1 | sort -n >/home/.sizes ) run nightly so I can keep a rough eye on my users' space consumption on the big shared machine.
  • chaos
    chaos about 15 years
    Please follow these steps. 1) Extend your PATH in your .bashrc. 2) Type 'bash'. 3) Type 'echo $PATH'. 4) Type 'bash'. 5) Type 'echo $PATH'. 6) Punch yourself in the head for ignorantly downvoting and insulting people because they know more about sysadmin best practices than you.
  • krx
    krx about 15 years
    I am impressed that you have a slightly valid reason, not going to punch myself in the face though. Its easy to get non-login shells where your path was not already extended. I take back that its dumb, I originally read it that you were trying to say you should not set important variables in your .bashrc or something.
  • Gareth
    Gareth about 15 years
    Perhaps someone should start a "Should I set my PATH variables in the .bashrc or .bash_profile"?
  • chaos
    chaos about 15 years
    @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.
  • Gareth
    Gareth about 15 years
    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!
  • dr-jan
    dr-jan about 15 years
    \w should give you the full pathname (unless you're within your home directory hierarchy when '/home/me' becomes '~' for example :-)
  • hookedonwinter
    hookedonwinter about 15 years
    It's the "except for" bit that I don't use \w. :-)
  • derobert
    derobert about 15 years
    The $? check is a pretty neat idea, I like it.
  • Sander Marechal
    Sander Marechal about 15 years
    There's a nice and simple linux command called "unp", the Unpacker that does this and more.
  • Dan Udey
    Dan Udey about 15 years
    If you set your login shell to be screen (and configure e.g. bash in your .screenrc), then whenever you SSH in, screen will automatically try to reconnect to disconnected screens. If that fails, it will create a new screen.
  • baudtack
    baudtack about 15 years
    @Dan Udey I haven't tried what you suggested myself, but the bash I posted will start the screen only on ssh logins were as setting screen as your login shell, would also start it on local logins. Which maybe what you want. It's just not what I want. :-)
  • Annika Backstrom
    Annika Backstrom about 15 years
    Your HISTCONTROL lines override each other, since it's just a shell variable. ignoreboth combines ignorespace and ignoredups.
  • devin
    devin about 15 years
    I use the ssh alias and ssh keys too... it makes every so easy
  • Léo Léopold Hertz 준영
    Léo Léopold Hertz 준영 about 15 years
    @Andrew: I run your first code unsuccessfully in OSX. It breaks my Prompt settings.
  • pgs
    pgs about 15 years
    I also show the status in my prompt, but keep the numeric value and colour it red if non-zero, otherwise green.
  • Léo Léopold Hertz 준영
    Léo Léopold Hertz 준영 about 15 years
    The command has one missing feature. It cannot open 7z package at boost.org/doc/libs/1_39_0/more/getting_started/… correctly. Do you know how to solve the problem?
  • Toby
    Toby about 15 years
    +1 for the export IGNOREEOF="2"
  • Rene Saarsoo
    Rene Saarsoo about 15 years
    +1 for the history control tips.
  • David Z
    David Z almost 15 years
    You could make 1up print a mushroom in ASCII art, just for kicks ;)
  • Rev316
    Rev316 over 14 years
    Works fine here (10.6.X)
  • Mayur Bhayani
    Mayur Bhayani about 14 years
    Newer versions of tar detect automatically the archive type, so can extract all supported formats by just 'tar xvf'.
  • user2910702
    user2910702 almost 14 years
    @Sander dtrx isn't bad at that either. It makes sure the archive extracts to its own subdirectory.
  • user2910702
    user2910702 almost 14 years
    I like your history -p trick.
  • user2910702
    user2910702 over 13 years
    It's easy enough to deploy your custom configuration on systems you regularly use, though.
  • Kish
    Kish about 12 years
    Will this alter the $? variable after running the command or does it still have the value produced by the last command run?
  • Rqomey
    Rqomey almost 12 years
    Do you also encrypt your history in that case? Why not encrypt your $home
  • Smyrnian
    Smyrnian almost 12 years
    While almost all of the answers refer to tweaking history, I haven't seen any which enable timestamping which can be useful. export HISTTIMEFORMAT='%F %T '
  • Sirex
    Sirex over 11 years
    you can put hostname aliases in .ssh/config to the same effect. In this case, add an entry 'Host cloudius' with 'username dinomite'
  • imapollo
    imapollo about 11 years
    Interesting....
  • jwbensley
    jwbensley about 11 years
    Just as a follow up to you ssh alias, this is something I do all the time. I always do this with the IP though in case of DNS outage.
  • jwbensley
    jwbensley about 11 years
    If you are worried about disconnects, check out mosh, I use it all the time and highly recommend it: mosh.mit.edu
  • Matthew G
    Matthew G over 10 years
    atool is a package that includes the commands apack and aunpack. They provide a convenient and consistent interface regardless of what the archive type is, and don't need any extra bash functions.
  • Matthew G
    Matthew G over 10 years
    This version of up() seems unnecessarily complex. I use this version: up() { cd $(eval printf '../'%.0s {1..$1}) && pwd; }. You can remove the call to 'pwd' if you wish obviously.
  • Matt Kenefick
    Matt Kenefick over 9 years
    I use something like this: # Directory navigation aliases alias ..='cd ..' alias ...='cd ../..' alias ....='cd ../../..' alias .....='cd ../../../..'