Shell tricks

Shared accounts

Sometimes, you have to use shell accounts which are shared with other people. Of course, everyone will adjust their settings, so if you're used to vi keybindings and your colleague prefers the default, you'll get in the way.

If you usually have the same IP address, here's a handy trick. Add the following lines to the .bashrc file and adjust the first variable. I'm assuming that you use ssh.

  MY_IP="10.0.0.126"
  FROM=`echo $SSH_CLIENT | cut -f1 -d" " | grep -v ":0"`
  case $FROM in
    *$MY_IP)
      # Enter your settings here
      set -o vi
      ;;
  esac

An alternative without using IP addresses:

  FROM_IP=$(echo $SSH_CLIENT | cut -f1 -d" " | grep -v ":0")
  FROM=$(host -t ptr $FROM_IP | cut -d" " -f5 | cut -d"." -f1)
  case $FROM in
    chara*)
      # Enter your settings here
      set -o vi
      ;;
  esac

If you use bash as your shell, this can be a lot shorter. The following example assumes that you usually log in via VPN, and the rest of your colleagues doesn't:

 VPN_NETWORK="172.30.1"
 FROM=${SSH_CLIENT%% *}   # Strip cruft from SSH_CLIENT environment variable
 case $FROM in
   $VPN_NETWORK*)
   set -o vi
   # Make more personal settings here
   ;;
 esac

for loop with whitespace as a field separator

When you have a file filenames.txt generated by for example find and you want to loop over in order to do something with the content, you'll find that your shell loop breaks over the spaces in filenames. To solve this, set the IFS internal variable:

  IFS="
  ";
  for i in `cat filenames.txt`
  do
    echo "$i";
  done;

Hostname in terminal emulator title

SSH'ing to a remote Solaris box from gnome-terminal or konsole will leave the window title incorrectly set. To correct this, put the following lines in your .bashrc if you're using bash on the other end (note that the ^G is created in vi by typing CTRL+V and then CTRL+G):

  PS1="[\u@\h \W]$ "
  PS1="\[\033]2;$USER@$HOSTNAME:\${PWD#$HOME/}^G$PS1"
  export PS1