Bash

From s5h.net

Jump to: navigation, search

Bash is my favourite shell.

Well, at work we often take a dated backup copy of a file that we might be editing. Some time ago I wrote a perl script that does some things to the file that is backed up. For example, if I was editing a zone file, why not increment the serial number inside it? This worked fine for a while, but later I decided it wasn’t such a good idea to have this on every single host that I work on. So, to cut a long story short, here’s the essential functionality implemented in bash so that it can exist in a .bashrc file, which is much easier to manage.

function bkp() {
 N=0;
 DATE=$( /bin/date +%Y%m%d );
 for i in $@ ; do
  D=$( /usr/bin/dirname $i );
  F=$( /bin/echo $i | /bin/sed -e 's/.*\///g' );
  if [ ! -d $D/old ] ; then
   /bin/mkdir -p $D/old;
  fi ;
  until [ 1 -eq 2 ] ; do
   let “N += 1″;
   C=$( /usr/bin/printf “%s/old/%s-%s-%.2d-%s” $D $F $DATE $N $USER );
   if [ ! -f $C ] ; then
    break ;
   fi ;
  done ;
  /bin/cp -p $i $C;
 done;
}

Hope this can be of some use to you too. This does have some obvious dependencies but this shouldn’t be too major.

Another great time saver is alt-backspace. Give that a go, it deletes as far as the first non-alphanumeric character. Alt . is also useful, returns the last argument on the previous command.

Don't forget about the curly bracket expansion:

user@laptop:~$ echo file{a,b,c}
filea fileb filec

This is notably very useful when you intend to create a large tree of items with identical nodes within.

$ mkdir -p {beta,current,release}/{code,scripts,html,images}

This would create the nodes code, scripts, html and images within the top directories beta, current, release. Much more useful than creating these individual items.

useful keystrokes

combination result
alt-. last arg from previous command
alt-d delete the next word on the line
alt-backspace delete backwards one word
ctrl-w delete backwards a whole word until white space/punctuation
ctrl-k delete from the cursor to the end of the line
ctrl-u delete from the cursor to the start of the line
alt-f move to the end of the word
alt-b move to the start of the word
ctrl-e move to the very end of the line
ctrl-a move to the very start of the line

in practice

Something useful that's worth remembering is that () can create a sub-shell where the output can be piped elsewhere.

( cmd1 ; cmd2 ) | cmd3

sends output from both cmd1 and cmd2 are sent as stdin to cmd3.

Personal tools
Google AdSense