Running a gpg shell script to decrypt a file via Automator

I regularly need to decrypt a gpg-encrypted file (always the same) to simply view it in TextEdit. I have a very simple shell script for that. It looks like this:

#!/bin/sh
outfile=`mktemp -t $$`  # Temporary file name
gpg --output $outfile --decrypt /path/to/file.gpg
open -a TextEdit $outfile
sleep 1
rm $outfile

When run from the terminal, all goes well. GPG asks for my passphrase in a pop-up window, TextEdit comes up, the temp file is deleted and all is great. Not so in Automator. I select "Run Shell Script", ignore the shell script input, paste the contents of the script (except for the first line). TextEdit pops up with a blank file and GPG never asks for the passphrase. I tried using the full path to GPG but that didn't do it. I know virtually nothing of Automator actions so the problem surely comes from me.

Any help appreciated!


The Automator “Run Shell Script” action runs the script in a non-interactive shell (for an explanation of the difference between interactive and non-interactive shells, see the pertinent section of the Advanced Bash Scripting Guide) – there is, simply spoken, no terminal to get user input from. I suppose the gpg utility recognizes this and skips the password prompt (else your script would hang).

You should be able to pipe your passphrase to GPG inside such an action using the --passphrase-fd 0 option (see gpg’s man page) , however, i.e.

echo "passphrase" |  gpg  --passphrase-fd 0 --output $outfile --decrypt /path/to/file.gpg

You can securely store your passphrase in the OS X Keychain and retrieve it from there. Although possible via a shell script (the TextMate blog has details on how to achieve that – be sure to read the comments), there are so many gotchas to that I’d recommend using a bit of AppleScript and Daniel Jalkut’s excellent Usable Keychain Scripting app. Once installed, the following bit of AppleScript will retrieve your password (assuming the account name is “GPG”):

tell application "Usable Keychain Scripting" to get password of first generic item of current keychain whose account is "GPG"

Either wrap it in an osascript shell command, i.e.

passphrase=$(osascript -e '<command above>')

or, as you are using Automator, add an AppleScript action, retrieve the passphrase inside it and pass it to the shell script.