An AppleScript to create a file in the current folder

Feb 24, '05 08:29:00AM

Contributed by: mysty

Even the best GUIs are challenged to ease the navigation through the plethora of files and folders on a typical set up. Say, for example, that after a bunch of searching or drilling down, you finally have before you the Finder window displaying the folder in which you want to work, and you want to create a file -- right there. Normally, I would launch my app of choice, say BBEdit, create my new file, and in the 'Save As...' dialogue, navigate all the way back down to wherever I had already found in the Finder to save the file in the right, deeply nested, spot.

Or, as I just discovered [Hints history, May 2001: Jump to locations in open/save dialogs], you can drag and drop the Finder folder window to the "Save As..." dialogue box to save that step (remember the trusty Default Folder cdev?). Still, this way, you have to have the windows positioned just so..

So below is a very basic AppleScript to create a file using the Unix command touch. I saved it as an application in Script Editor, and then added the resulting application to the toolbar above Finder windows (drag and hover, then drop the app when you see the green "plus" icon), so I can create a file in any Finder window I am looking at.

try
  tell application "Finder" to set the this_folder ¬
   to (folder of the front window) as alias
on error -- no open folder windows
  set the this_folder to path to desktop folder as alias
end try

set thefilename to text returned of (display dialog ¬
 "Create file named:" default answer "filename.txt")
set thefullpath to POSIX path of this_folder & thefilename
do shell script "touch \"" & thefullpath & "\""
I tend to drag the resulting file onto an app using QuickSilver, so I don't really mind that the creator/filetype are set to TextEdit. BBEdit, for example, then learns which directory I want to be in and this saves me a bunch of time navigating about. I am sure there are neater ways to do this, but it works for me. Credits due to other authors on this site for respective code fragments...

Comments (9)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20050219134457298