Friday, February 28, 2014

Open different file types with the same command (Linux)

Sometimes on the command prompt I want to open files without worrying about which application to use for it. Just like with double clicks and file associations. Set this function in your ~/.bashrc and then just use "view <filename>" to render it in the correct application.
function view() {
 if [ $# == 0 ]; then
  echo "usage: $0 <file1> [ <file2> ... ]"
 fi

 OLD_IFS=$IFS
 IFS=""

 for ARG in "$@"; do

  if [ -f "$ARG" ]; then

   MIME=$(file -b --mime-type "$ARG")
   MIME_1=${MIME%/*}

   case "$MIME" in
    application/pdf)
     evince "$ARG" &
     continue;;

    application/zip | application/x-gzip | application/x-bzip2)
     file-roller "$ARG" &
     continue;;

    application/vnd.ms-excel)
     libreoffice --calc "$ARG" &
     continue;;

    application/msword)
     libreoffice --writer "$ARG" &
     continue;;
   esac

   case "$MIME_1" in
    archive)
     file-roller "$ARG" &
     continue;;

    image)
     eog "$ARG" &
     continue;;

    text)
     sublime_text "$ARG"
     continue;;
   esac
   echo "No handler known for type $MIME"
  fi

 done
 IFS=$OLD_IFS
}
And then re-source you Bash shell:
source ~/.bashrc
You're good to go. You might want to modify the file handlers / add some more to match your own setup.

No comments:

Post a Comment