13 December 2012

A Simple Bash open() function That Is Platform Independent.

I use Bash as my shell of choice. This is partly laziness, I learnt Bash first and it has always been the default on clean installs, and also because if I end up on a server or a machine that has just been set up I know what I am doing and don't miss fancy functionality provided by other shells. That's not to say that on my To Do list for 2013 is to learn more about zsh.

One of the tasks I have been trying to do over the last couple of months is tame my dot-files. In doing this I have been trying to clean up functions that I have added to my .bashrc and make them more machine/platform independent. (Once I have done this I will write up how I have structured my dot-files and point you to my GitHub repo).

One of my more frequently used functions is open(). I use Bash extensively on Windows via Cygwin as well as on *nix machines. The aim of the function I started out with was to allow me to open files directly from Cygwin's Bash shell that were standard Windows files (such as Word and Excel files). Since I got in the habit of using the function on Windows I wanted something that worked the same on Linux. Below is the (very) simple function I ended up with

 1 function open()
 2 {
 3     UNAME=`uname`
 4     OSLINUX="Linux"
 7     if [ "$UNAME" = "$OSLINUX" ]; then
 8         if [ "$1" = "" ]; then
 9             echo "open Failed, No file specified to open."
10         else
11             xdg-open "$1"
12         fi
13     elif [ "$UNAME" = "$OSCYGWIN" ]; then
14         if [ "$1" = "" ]; then
15             NATIVE_PATH="."
16         else
17             NATIVE_PATH="$1"
18         fi
20         WIN_PATH=`cygpath -w -a "${NATIVE_PATH}"`
21         cmd /C start "" "$WIN_PATH"
22     fi
23 }

I am sure that the function will be cleaned up some more and made simpler however, it works as I need it to in the 5 mins I worked on it.

The function use's xdg-open which is desktop independent on Linux so it should "just work" otherwise on Cygwin it just uses 'cygpath' to generate the correct file path before using 'cmd' to launch the path.

Please Note :: The path provided to cmd is hard coded to my C:\ drive. I have long given up on using partitioned Windows disks so I took the lazy route here.

Once added to your .bashrc you can just call $open file or $open . or $open ../ to open a file or open the File Manager in the current directory or parent directory.

No comments: