Using Shell Scripts

Hazel can use shell scripts, or even standalone command-line programs, in either conditions or actions. In a condition, the shell script tells Hazel whether or not the file or folder being processed matches. In an action, the shell script can do pretty much anything (which may involve the file or folder being processed, but doesn’t have to). Scripts can be written in any language (including Perl or Python), as long as you tell Hazel which shell or interpreter to use.

Like AppleScript, JavaScript, and Automator, shell scripts enable Hazel to do things it’s unable to do on its own. For example, a shell script in a condition could employ the  grep  command to perform sophisticated pattern-matching on the file using regular expressions. A shell script in an action, likewise, can process the matched file or folder using any of innumerable command-line utilities. If you’re already comfortable writing shell scripts, using them in Hazel should be quite natural.

Unlike AppleScript and JavaScript, shell scripts in Hazel can neither accept import attributes nor export custom attributes. Shell scripts take just one argument,  $1 , which is the full path of the file or folder being processed.

When working with shell scripts in Hazel, keep the following in mind:


Embedded vs. External Shell Scripts

Hazel can run scripts in either of two ways:


Shell Scripts in Rule Conditions

The goal of any script used in a rule condition (via the “Passes shell script” attribute) should be to perform a logical test that either succeeds (the condition matches) or fails (the condition does not match). Bear in mind the following:


Shell Scripts in Rule Actions

When you use the “Run shell script” action, a successful match can cause any script to run—even one that has nothing to do with the file or folder you’re processing. However, most of the time you will probably want to use the shell script to perform an action on the matched file or folder, in which case your script can refer to it with the argument  $1 , which represents its path.

For example, this simple script uses text-to-speech to say the entire path of whatever file or folder has matched the rule condition(s):

#!/bin/bash

say "The file $1 matches this rule’s conditions."

As is the case when using shell scripts in conditions, scripts used in the “Run shell script” action should return an exit status of 0 to indicate that the action was performed successfully. Any other value indicates an error, which causes Hazel to execute the rule again repeatedly until the action succeeds. (Once again, see  this page  for exit status examples for bash scripts.)

SEE ALSO

Using AppleScript or JavaScript

Using Automator