Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

Write an Alfred Extension to Create Files on the Fly

by
This post is part of a series called Taming The Terminal.
Quick Tip: Lightning Fast File Creation with Terminal

Recently, we took a look at how to use Terminal to quickly create files. Today, we're going to review and apply this knowledge to make our own Alfred extension that creates a new directory of files in an instant. We'll even hit on some AppleScript along the way so you can really get your dose of geeky goodness.


What We're Building

As a developer, whenever I begin a new project, I typically run through the same process. First, I have to create a folder and then name it. Then I have to open a text editor and individually create each file that I want included (index.html, style.css, etc.).

Obviously, this is a pain, so I've tried a bunch of things to get around it. I tried keeping a blank project on hand that I can just drag and copy, using Terminal to create the files manually, the works.

My current favorite method though is to call up Alfred, type in the name of the folder that I want to create and hit Return. That's it! All of the rest of the steps are completely automated, saving me plenty of time in a given week.

Obviously, this functionality doesn't come with Alfred out of the box, so we'll have to build it in. Fortunately, doing so is pretty simple!

Tip: This tutorial isn't just for developers. Follow along and tweak it to create files of any type!


Terminal Homework

As I mentioned in the introduction, I've covered Terminal file creation basics in a previous article, but they're worth mentioning again here just so we're all on the same page.

There are three basic shell script commands that we'll be using today: cd, mkdir and touch. Let's see how each works.

Changing Your Directory

By default, when you open up Terminal, you should begin in your Mac's home folder. This will serve as the starting point for any commands that require a location. If you want to change that location, you use the cd command.

cd Desktop/

This tells the Terminal that you want to change the current directory to "Desktop." Later when we do this from Alfred, we'll need to be a little more specific:

/Users/MacBookPrime/Desktop

Here I've included the full path to my Desktop folder. It's extremely important that you customize this particular snippet for your own machine. To do that, replace my user name with your own. Insert your user name between "Users/" and "Desktop/" in the snippet below:

/Users/YourUserNameGoesHere/Desktop

Making a New Directory

Once we change directories, we'll need to create a new directory (folder). To do this, we use the mkdir command.

mkdir mySite

This will create a new folder named "mySite" in the current directory. In our case, this will be the Desktop.

Making a New File

Now comes the best part: how to create a new file. For whatever reason, it seems silly to me that I have to open an app to create a file. I should just be able to bust out empty files, with any extension that I want, purely at will. With the touch command, we can do exactly that:

touch textFile.txt

This will create a new plain text file in the current directory with the name "textFile.txt." Easy right?

Put It All Together

Now we have all of the knowledge that we need to pull off our shell script. Here's what it looks like when we combine these commands (scroll right to see entire snippet).

cd /Users/MacBookPrime/Desktop; mkdir mySite; cd mySite; touch index.html style.css script.js

Notice that different commands are separated by a semicolon and also that touch commands can be chained together using only a space between the various file names.

Creating an Alfred Extension

Now that we have our basic shell script figured out, it's time to actually create the Alfred extension. Fortunately, we don't need any special developer tools for this, just Alfred! You will need the Powerpack though, which is the premium version of Alfred.

Step 1. Create a New Extension

To begin, fire up Alfred and click on the tiny gear in the upper right to bring up the Preferences. From here, click on the "Extensions" tab. You might or might not have a few third party extensions already in here.

Alfred
Click on the Extensions Tab

From the Extensions tab, click on the little plus button at the bottom left of the window. That should pop up a menu of the various types of extensions that you can create:

Alfred
Choose "Shell Script"

From here, choose "Shell Script." Don't worry if you have no idea how to write a shell script, we already wrote one above!

Step 2. Name and Other Details

When you create a new extension, you can give it a name and insert your information in case you're going to be distributing it. This way people can see who it's from.

Alfred
Enter the credit information and hit Save

Additionally, you can customize the icon. I think the Terminal icon is just fine for our purposes but feel free to drag in your own image.

Step 3. Enter Alfred Details

Next, you'll need to enter the title, description and keyword of the extension.

Alfred
Enter the Details for Alfred here

This may seem a little redundant with the previous window but it's not. The screen before was just for credit purposes, this determines what information Alfred actually shows when you access the extension.

Alfred
Alfred shows the details you entered when you call the extension

Notice that I set "nw" as the shortcut, so when I type this into Alfred, the first option that pops up shows the title and description that I entered.

Step 4. Enter the Script

Now it's time to enter in the shell commands that we wrote before, with a little customization. Here's the snippet from before:

cd /Users/MacBookPrime/Desktop; mkdir mySite; cd mySite; touch index.html style.css script.js

Now, rather than making a folder called "mySite" every time, let's use the text that the user enters into Alfred. We do this by replacing mySite with {query}.

cd /Users/MacBookPrime/Desktop; mkdir {query}; cd {query}; touch index.html style.css script.js

This setup requires entry from the user so be sure to set the "Parameter" setting to "Required Parameter." Also, don't forget to customize the path to your desktop.

Alfred
Enter the script into the Command field

Once you're done with that step, hit the Save button. That's it! You're all finished.

Test Out the Extension

To make sure everything worked properly, exit the Preferences window and launch Alfred again. Type "nw" for the shortcut, followed by the name of the folder that you want to create.

Alfred
Trying out the new extension

The result of the extension should be a folder with the name you chose full of the files that you created with the touch command.

Alfred
The Result of the Extension

If it works, then you're done. The next steps are completely optional. If you're up for a challenge, proceed!

Advanced: Make It Work in Any Folder

The method above always creates a new folder on your Desktop. In truth, this is how a lot of people work, but I never recommend such messy practices. I'm a big proponent of keeping your Desktop clean, so I set out to make the script better.

What we want to do is query the Finder and grab the path of the frontmost window. If no window exists, we should default to the Desktop. Then later when we create the files, we'll use the path from the first step. In practice, you'll be able to navigate to a folder on your drive, then run the Alfred extension and quickly create a new directory full of files.

Step 1. AppleScript to the Rescue

Obviously, the tricky part here is getting a shell script to automatically figure out the frontmost Finder window at any given time. As it turns out, the easiest way that I know to inspect a Finder window is AppleScript. For double nerd points, you can actually wrap an AppleScript into a shell script, and vice versa.

The script that we need will have a few basic steps:

  1. Try to get the path of the frontmost Finder window
  2. If the try is successful, return the path of that window
  3. If the try fails (no Finder window exists), return path of Desktop

A speed bump that we run into on this journey is that, by default, AppleScript uses a different format for file paths than shell scripts. Instead of the forward slash that you're probably used to (Users/Username/Desktop), AppleScript uses colons to separate directories (Users:Username:Desktop).

This is easy enough to handle though. We just have to be sure to refer to the POSIX path in our script. Here's what the finished product looks like.

[applescript]
try
tell application "Finder"
set this_folder to (the target of the front window) as alias
set this_folder to POSIX path of this_folder
return this_folder
end tell
end try

set this_folder to POSIX path of (path to desktop)
return this_folder
[/applescript]

As you can see, we simply walked through each of the steps that we outlined above. The result of this script will always be a file path. In the next few steps, we'll see how to use that path in our shell script.

Step 2. Reformatting the Script

Our next task is to embed the AppleScript that we just wrote into our shell script. To do this, we use the following syntax:

osascript -e 'AppleScript goes here'

As you can see, we use "osascript" to begin out AppleScript embed. The next piece, "-e" is used to separate different lines, which are each encased in single quotes. So if we wanted to embed multiple lines of AppleScript, it would look like this:

osascript -e 'tell application "Finder"' -e 'activate' -e 'end tell'

This is a very basic, three line script split up by -e switches. With this knowledge in mind, we need to reformat our script above. Doing this can get a little confusing, so I like to follow a very specific pattern. First, strip out the indentation and extra whitespace.

try
tell application "Finder"
set this_folder to (the target of the front window) as alias
set this_folder to POSIX path of this_folder
return this_folder
end tell
end try
set this_folder to POSIX path of (path to desktop)
return this_folder

Next, wrap each line in a single quote and precede it with -e so the shell script can parse the different lines.

-e 'try'
-e 'tell application "Finder"'
-e 'set this_folder to (the target of the front window) as alias'
-e 'set this_folder to POSIX path of this_folder'
-e 'return this_folder'
-e 'end tell'
-e 'end try'
-e 'set this_folder to POSIX path of (path to desktop)'
-e 'return this_folder'

Finally, strip out all of the line breaks and place the osascript command at the beginning.

osascript -e 'try' -e 'tell application "Finder"' -e 'set this_folder to (the target of the front window) as alias' -e 'set this_folder to POSIX path of this_folder' -e 'return this_folder' -e 'end tell' -e 'end try' -e 'set this_folder to POSIX path of (path to desktop)' -e 'return this_folder'

Step 3. Toss it All Together

For our final trick, we're going to use the path returned from the AppleScript as the starting point for our shell script that creates the files. To do this, we need to toss the result of the script into a variable, then call that variable when we need a starting path.

Before we look at the completed shell script, let's look at the syntax for assigning the variable:

myPath=$(osascript -e 'AppleScript goes here')

Here we created a variable called "myPath" and then set it to an AppleScript. Since this will return a path, we can then use this variable in place of a path.

cd $myPath;

That's all there is to it. Now let's toss all of this stuff together into one giant command.

myPath=$(osascript -e 'try' -e 'tell application "Finder"' -e 'set this_folder to (the target of the front window) as alias' -e 'set this_folder to POSIX path of this_folder' -e 'return this_folder' -e 'end tell' -e 'end try' -e 'set this_folder to POSIX path of (path to desktop)' -e 'return this_folder'); cd $myPath; mkdir {query}; cd {query}; touch index.html style.css script.js

Success!

The command should now be fully functional. Paste it into Alfred and give it a test drive using the same "nw" prefix as before. The result should be a new folder in your current Finder window with the name that you passed in as a parameter.

Alfred
Paste the finished script into the Command field

Make Your Own

If you made it all the way through this tutorial, congratulations, that was quite the challenge! You have now hand coded your first Alfred extension. With your newfound knowledge on combining shell scripts and AppleScripts, you should be able to create some pretty fantastic extensions all on your own.

If you have any ideas for new extensions or have created some on your own, leave a comment below and let us know.

Advertisement