Monday, February 01, 2010

scpdiff

I often work on the same files across multiple computers (home, office, laptop) and I often wants to compare the work. This often involve copying a remote file locally, careful not to replace and existent file.

For convenience, I wrote the following function in my .bashrc:


# .bashrc
# usage scpdiff [DIFFOPTS] LFILE RFILE
# assumes the last two arguments to be the files to be compared
scpdiff() {
  local DIFFOPTS="";
  local LFILE=""; local fl='';
  local FILECOUNT=0;
  local RFILE=""; local fr='';

  while (( "$#" )); do
    if [ "$#" -gt 2 ]; then
      DIFFOPTS="${DIFFOPTS} ${1}";
    elif [ "$#" -eq 2 ]; then LFILE=$1;
      let "FILECOUNT = FILECOUNT + 1";
    elif [ "$#" -eq 1 ]; then
      RFILE=$1;
      let "FILECOUNT = FILECOUNT + 1";
    fi
    shift;
  done

  [ ! ${FILECOUNT} -eq 2 ] \
  && printf "Needs exactly 2 files to diff.\n" > /dev/stderr \
  && return 1;

  fl="/tmp/$(basename ${LFILE}).l";
  ( ! scp "${LFILE}" ${fl} >& /dev/null ) \
  && printf "${LFILE} Not Found\n" \
  && return 1;
  fr="/tmp/$(basename ${RFILE}).r";
  ( ! scp "${RFILE}" ${fr} >& /dev/null ) \
  && printf "${RFILE} Not Found\n" \
  && return 1;

  # Allows customization using different DIFFTOOL
  [ -z ${DIFFTOOL} ] && local DIFFTOOL="diff";
  ${DIFFTOOL} ${DIFFOPTS} ${fl} ${fr};
  
  rm -f ${fl} ${fr};
}

No comments: