Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Changing the Finder "Open With" contextual menu from the command line

The command line tool duti (http://duti.sourceforge.net) can be used to change default file-application launching associations as shown by the Finder "Open With" contextual menu. Changing the Finder "Open With" contextual menu means changing the default way we "open" documents on the command line as well.

The "lsregister" command can be used to dump or rebuild the Launch Services database.

export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
export IFS=$' \t\n'


# download & install duti, MacVim and TextMate

# duti - set default UTI handlers
# cf. http://duti.sourceforge.net/documentation.php and
# http://developer.apple.com/macosx/uniformtypeidentifiers.html

cd ~/Desktop
curl -L -O http://downloads.sourceforge.net/duti/duti-1.3.0.pkg.tar.gz
tar -xzf duti-1.3.0.pkg.tar.gz
open -a Installer duti-1.3.0.pkg
stat -x /usr/local/bin/duti
duti -h
man duti


# MacVim, http://code.google.com/p/macvim/

cd ~/Desktop
curl -L -O http://macvim.googlecode.com/files/MacVim-7_2-stable-1_2.tbz
tar -xjf MacVim-7_2-stable-1_2.tbz
#open MacVim-7_2-stable-1_2.tbz    # uses BOMArchiveHelper (10.4) or Archive Utility (10.5) respectively
mv -i MacVim-7_2-stable-1_2 MacVim
mv -i ~/Desktop/MacVim /Applications


# TextMate, http://macromates.com

cd ~/Desktop
curl -L -O http://macromates.com/textmate/files/TextMate_1.5.7.dmg
hdiutil mount ~/Desktop/TextMate_1.5.7.dmg
cp -Ri '/Volumes/TextMate 1.5.7/TextMate.app' /Applications
hdiutil unmount '/Volumes/TextMate 1.5.7'
#/usr/bin/sudo /bin/ln -s /Applications/TextMate.app/Contents/Resources/mate /usr/local/bin/mate


# get the path to the "lsregister" command
locate lsregister | head -n 1
find /System/Library/Frameworks -type f -name lsregister -ls
find /System/Library/Frameworks/CoreServices.framework -type f -name lsregister -ls

alias lsregister="/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister"

#/usr/bin/sudo /bin/ln -s `locate lsregister | head -n 1` /bin/lsregister   # alternative

# rebuild Launch Services database
#alias rlsdb='lsregister -kill -r -f -all system,local,user'    # Mac OS X 10.5; cf. http://9stmaryrd.com/2008/05/16/158
alias rlsdb='lsregister -kill -r -f -domain local -domain system -domain user'

rlsdb

lsregister -h

lsregister -dump | grep -i duti
lsregister -dump | grep -i MacVim
lsregister -dump | grep -i TextMate
lsregister -dump | grep -i TextEdit
lsregister -dump | grep -i Safari
lsregister -dump | grep -i helpviewer


lsregister -dump | sed -E -n -e 's/^.*uti:[[:space:]]+(.*)$/  \1/p' | sort | uniq | nl
lsregister -dump | grep '[[:space:]]uti:' | awk '{ print $2 }' | sort | uniq | nl
lsregister -dump | sed -E -n -e 's/^.*identifier:[[:space:]]+([^[:space:]].*)$/  \1/p' | sort | uniq | nl
lsregister -dump | sed -E -n -e 's/^.*path:[[:space:]]+([^[:space:]].*\.app)$/  \1/p' | sort | uniq | nl


lsregister -dump | sed -E -n -e 's/^.*uti:[[:space:]]+(.*)$/  \1/p' | nl | egrep -i 'duti|MacVim|TextMate|TextEdit|Safari|helpviewer'
lsregister -dump | sed -E -n -e 's/^.*identifier:[[:space:]]+([^[:space:]].*)$/  \1/p' | nl | egrep -i 'duti|MacVim|TextMate|TextEdit|Safari|helpviewer'
lsregister -dump | sed -E -n -e 's/^.*path:[[:space:]]+([^[:space:]].*\.app)$/  \1/p' | nl | egrep -i 'duti|MacVim|TextMate|TextEdit|Safari|helpviewer'


lsregister -dump | sed -E -n -e 's/^.*uti:[[:space:]]+(public\..*)$/  \1/p' | sort | uniq | nl
lsregister -dump | sed -E -n -e 's/^.*uti:[[:space:]]+(.*text.*)$/  \1/p' | sort | uniq | nl


alias utis="lsregister -dump | grep '[[:space:]]uti:' | awk '{ print \$2 }' | sort | uniq"
alias utis="lsregister -dump | sed -E -n -e 's/^.*uti:[[:space:]]+(.*)$/\1/p' | sort | uniq"
utis

utis | grep -i 'public\.' | nl

defaults read com.apple.LaunchServices


# ... or just use wsupdate from http://osxutils.sourceforge.net 
# move & copy the same file
unset -f mc
function mc() {
   if [[ $# -gt 1 ]] || [[ ! -e "$@" ]]; then return 1; fi
   tmpfile="${@}.tmp-${RANDOM}"
   printf "%s\n" "$tmpfile"
   /bin/mv "$@" "${tmpfile}"
   /bin/sleep 0.2
   /bin/cp -p "${tmpfile}" "$@"
   /bin/rm "${tmpfile}"
   return 0
}


unset -f mc
function mc() {
   if [[ $# -gt 1 ]] || [[ ! -e "$@" ]]; then return 1; fi
   tmpfile="/tmp/tmpfile.tmp-${RANDOM}"
   printf "%s\n" "$tmpfile"
   /bin/mv "$@" "${tmpfile}"
   /bin/sleep 0.2
   /bin/cp -Rp "${tmpfile}" "$@"
   /bin/rm -Rf "${tmpfile}"
   return 0
}



echo hello world > ~/Desktop/test.txt
echo hello world > ~/Desktop/test.html


# switch between Safari & Help Viewer as the default launching app for html files
open ~/Desktop/test.html


# cf. http://duti.sourceforge.net/documentation.php

printf "%s\n" 'com.apple.helpviewer   public.html   all' | duti     
#mc ~/Desktop/test.html
wsupdate ~/Desktop/test.html
open ~/Desktop/test.html

printf "%s\n" 'com.apple.Safari   public.html   all' | duti
wsupdate ~/Desktop/test.html
open ~/Desktop/test.html

rlsdb


# switch between TextEdit, MacVim & TextMate as the default launching app for plain text files

open ~/Desktop/test.txt

printf "%s\n" 'com.macromates.textmate   public.plain-text   all' | duti
open ~/Desktop/test.txt
wsupdate ~/Desktop/test.txt

printf "%s\n" 'org.vim.MacVim   public.plain-text   all' | duti
open ~/Desktop/test.txt    # type: ":q" or ":x" to quit test.txt
wsupdate ~/Desktop/test.txt

printf "%s\n" 'com.apple.TextEdit   public.plain-text   all' | duti
open ~/Desktop/test.txt
wsupdate ~/Desktop/test.txt



# cf. http://duti.sourceforge.net/documentation.php

/bin/cat > ~/Desktop/test.duti <<-'EOF'
com.apple.helpviewer   public.html   all
com.macromates.textmate   public.plain-text   all
EOF

# remove white space at line beginning
ed -s ~/Desktop/test.duti <<< $',s/^[[:space:]]*//\nw'

open -e ~/Desktop/test.duti

duti -v ~/Desktop/test.duti

wsupdate ~/Desktop/test.html
open ~/Desktop/test.html

wsupdate ~/Desktop/test.txt
open ~/Desktop/test.txt


#--------------------------------------------------


# GUI alternative to switch the default launching app for a single file
[right-click on a file] + [alt]  ->  "Always Open With"

# GUI alternative to change the default launching app for all files of the same kind
[right-click on a file] -> "Get Info" -> "Open with:" -> [select an app] -> "Change All ..."

"openterminal" contextual menu item with Automator

Right-click on a file or folder in a Finder window and select Automator -> openterminal to open it in Terminal.app.
(i.e. cd to the folder or open the file in the nano text editor)

open -a Automator

#--------------------------------------------------

Drag or add actions here to build your workflow:
Library: Finder -> Action: Get Selected Finder Items
Library: Automator -> Action: Run Shell Script
                                 - Shell: /bin/sh
                                 - Pass input: as arguments


if [[ $# -gt 1 ]]; then exit 0; fi

if [[ -d "$@" ]]; then

   printf "%s" "$@" | /usr/bin/pbcopy
   #/usr/local/bin/cpath # cf. http://osxutils.sourceforge.net

   /usr/bin/open -a Terminal

   /usr/bin/osascript -e 'tell application "Terminal" to do script with command "printf \"\\e[8;26;115;t\"; printf \"\\e[3;300;240;t\"; cd \"$(/usr/bin/pbpaste)\"; /usr/bin/clear" in (first window whose name contains " ")'

# alternative without /usr/bin/clear (experimental)
# requires:
# defaults write com.apple.Terminal Autowrap NO
# or:
# Terminal menu -> Window Settings ...  -> Buffer -> in the Scrollback 
# section check the box next to "Wrap lines that are too long" 
# -> click "Use Settings as Defaults"

#   /usr/bin/osascript -e 'tell application "Terminal" to do script with command "cd \"$(/usr/bin/pbpaste)\"; /usr/bin/tput cup 0 0; /usr/bin/tput dl1; /usr/bin/tput el; /usr/bin/tput dl1; /usr/bin/tput el" in (first window whose name contains " ")'

   exit 0

elif [[ -r "$@" ]]; then 

   printf "%s" "$@" | /usr/bin/pbcopy

   /usr/bin/open -a Terminal

   /usr/bin/osascript -e 'tell application "Terminal" to do script with command "printf \"\\e[8;26;115;t\"; printf \"\\e[3;300;240;t\"; /usr/bin/clear; /bin/sleep 0.3; /usr/bin/nano \"$(/usr/bin/pbpaste)\";" in (first window whose name contains " ")'

exit 0

fi

exit 0


# now save the openterminal Automator workflow as a contextual menu item:
# Automator -> File -> Save As Plug-in ... -> Save Plug-in As: openterminal -> Plug-in for: Finder -> click Save


#--------------------------------------------------


open -a Automator ~/Library/Workflows/Applications/Finder/openterminal.workflow

/usr/bin/automator ~/Library/Workflows/Applications/Finder/openterminal.workflow >/dev/null 2>&1


More on how to cd effectively:

- cdto - Finder Toolbar button to open a Terminal window
- History of visited directories in BASH
- bash Tips and Tricks: $CDPATH
- Bash Shell Customisation: cdable_vars
- The Definitive Guide to Bash Command Line History
- Working Productively in Bash's Vi Command Line Editing Mode (with Cheat Sheet)
- Leopard's bash auto-completion vs. symlinked directories
- zg.rb (ZoomGo)
- fuzzy_file_finder.rb
- cd to Directory within Terminal
- Pimp my shell
- Per-directory bash history
- Terminal Tricks: A Fuzzy cd Command
- Cdots - Change directory back - 1-7 times - and forth with TAB-completion
- Fine-tuning tab completion in Bash
- recd on sourceforge
- recd - cd again via regular expression
Download with: curl -L -O http://heanet.dl.sourceforge.net/sourceforge/recd/recd.sh

newfolder contextual menu item with Automator

Right-click on a folder in a Finder window and select Automator -> newfolder to create a "NewFolder".


open -a Automator

#--------------------------------------------------

Drag or add actions here to build your workflow:
Library: Finder -> Action: Get Selected Finder Items
Library: Automator -> Action: Run Shell Script
                                 - Shell: /bin/sh
                                 - Pass input: as arguments

current_dir="$@"
name_of_new_dir="NewFolder"

if [[ -d "${current_dir}" ]] && [[ -w "${current_dir}" ]]; then
   /bin/mkdir -p "${current_dir}${name_of_new_dir}"
fi

exit 0


# now save the newfolder Automator workflow as a contextual menu item
Automator -> File -> Save As Plug-in ... -> Save Plug-in As: newfolder -> Plug-in for: Finder -> Save

#--------------------------------------------------

open ~/Library/Workflows/Applications/Finder/newfolder.workflow

# now open your Home directory, right-click on a folder and select Automator -> newfolder to create a "NewFolder" 
open ~

virusscan contextual menu item with Automator

Right-click on a file or folder and select Automator -> virusscan to scan the selected Finder item for viruses.
Requires Automator (Mac OS X 10.4 or later), ClamAV (man clamdscan) and CocoaDialog (for the notification pop-up).
See also: Compile ClamAV from source on Mac OS X and Update to ClamAV 0.94


# get the ClamAV icon
cd ~/Desktop
curl -L -O http://freshmeat.net/redir/clamav/29355/url_tgz/clamav-0.92.tar.gz
tar -xzf clamav-0.92.tar.gz
cd clamav-0.92
sudo cp ~/Desktop/clamav-0.92/docs/html/img2.png /usr/local/bin/CocoaDialog.app/Contents/Resources/clamav.png
#sudo sips -i /usr/local/bin/CocoaDialog.app/Contents/Resources/clamav.png
sudo chown -R root:wheel /usr/local/bin/CocoaDialog.app
sudo chmod -R 0755 /usr/local/bin/CocoaDialog.app


open -a Automator


#----------------------------------------------------


Drag or add actions here to build your workflow:
Library: Finder -> Action: Get Selected Finder Items
Library: Automator -> Action: Run Shell Script
                                 - Shell: /bin/bash
                                 - Pass input: as arguments

cocoadialog="/usr/local/bin/CocoaDialog.app/Contents/MacOS/CocoaDialog"
CD_Resources="/usr/local/bin/CocoaDialog.app/Contents/Resources"

for f in "$@"; do

   # remove a trailing slash character "/" if necessary
   /usr/local/bin/clamdscan -v "${f%/}"
   #/opt/local/bin/clamdscan -v "${f%/}"

   #/opt/local/bin/clamdscan --quiet "$f" 2>/dev/null


   return_code=$?

   if [[ $return_code -eq 0 ]]; then
 
      /usr/bin/say OK

      $cocoadialog bubble --no-timeout --x-placement center --y-placement center --background-top "00FF00" \
          --background-bottom "00FF99" --icon-file $CD_Resources/clamav.png --title "Scanned item is OK!" \
          --text "$f"

   elif [[ $return_code -eq 1 ]]; then

      /usr/bin/say "virus alert"

      $cocoadialog bubble --no-timeout --x-placement center --y-placement center --background-top "FF0000" \
          --background-bottom "FF0066" --icon-file $CD_Resources/clamav.png --title "WARNING: VIRUS ALERT!!!" \
          --text "$f"

   else

      $cocoadialog bubble --no-timeout --x-placement center --y-placement center --background-top "FFCC00" \
          --background-bottom "FFCC33" --icon-file $CD_Resources/clamav.png --title "ClamAV virus scan failed!" \
          --text "Please, check your ClamAV setup! Return code of man clamdscan: $return_code"

      exit 1

   fi

done

exit 0


#----------------------------------------------------


# save the virusscan Automator workflow as a contextual menu item
Automator -> File -> Save As Plug-in ... -> Save Plug-in As: virusscan -> Plug-in for: Finder -> Save

open ~/Library/Workflows/Applications/Finder/virusscan.workflow

# test some files in ...
open ~/Desktop/clamav-0.92/test

Speed up Gnome menus

// description of your code here
Speed up the gnome menus by removing display delay
// insert code here..
gtk-menu-popup-delay = 0"| tee -a .gtkrc-2.0

#Now save the file in you home directory under the name .gtkrc-2.0 and restart your x session