Platform independent .bashrc file

The number of computers I have accounts on has recently exploded, and manually editing my .bashrc file on each of these computers started getting tedious. I decided to resolve this by writing a single .bashrc file that can be copied over to all my accounts. This allows me to maintain a single master file, but requires me to set configurations conditional on the account the file is on. Here, I describe some of the things I did.

Firstly, I finally spent a few hours learning bash by readingĀ Learning the bash Shell. I recommend you do this too. You’ll easily make up the hours in increased productivity.

My conditional settings are dependent on the kind of operating system I’m running and the particular machine I’m on. Let’s put this information in two variables:

os=`uname -s`
host=`hostname | cut -d. -f1`

Passing the result of hostname to cut causes host to be set to just the first part of your hostname. For example, foo instead of foo.bar.com. This allows me to type less in later code.

Now, as an example, on one of my computer accounts I was using a software called Netkit. This required setting some environment variables and sourcing a file that provided bash completion features. Assuming the hostname was net.cs.yale.edu, I did this with:

if [ $host = "net" ]; then
    export NETKIT_HOME=/usr/local/netkit
    MANPATH=$NETKIT_HOME/man:$MANPATH
    PATH=$NETKIT_HOME/bin:$PATH
    . $NETKIT_HOME/bin/netkit_bash_completion
fi

With this code, my environment variable namespace is not polluted on all my other accounts, and I won’t get any errors at login aboutĀ netkit_bash_completion not being found.

Some settings depend on the OS. For example, I like to colorize the output from ls, but the option for this differs on Mac and Linux systems. I can use a bash case construct to set the alias appropriately:

case $os in
    "Darwin" )
        alias ls='ls -G';;
    "Linux"  )
        alias ls='ls --color=auto';;
esac

As one more example, I define aliases to help me ssh between all my machines more easily. There’s no point in setting this up for the machine you’re on, so I do:

[ $host != "net" ] && alias ssh_net='ssh user_name@net.cs.yale.edu'

Now all you have to do is create another bash script that rsync’s your .bashrc file to all your accounts, and run it every time you make a change.

This entry was posted in Uncategorized and tagged . Bookmark the permalink.

One Response to Platform independent .bashrc file

  1. Ben says:

    Great guide, thanks for posting.

    Because I ssh into several different servers with generic usernames (e.g. login01), I found it more useful to use the other part of the hostname rather than the first field.

    I used the following command to obtain this:

    host=`echo $(hostname) | sed “s/$(echo “$(hostname -s)\.”)//g”`

    to obtain “ls4.tacc.utexas.edu” instead of “login2″ from “login2.ls4.tacc.utexas.edu”

Leave a Reply