Escaping Unix special characters from 'POSIX Path' command

Apple’s “POSIX Path of…” command doesn’t ‘escape’ any of the special Unix characters when it returns the path to you. This means if you try to use that file path in a shell script, it just might fail if the path contains any special characters (like a space, etc.).

This script assumes you are passing it a unix file path and escapes the special characters with a \ character.

OS version: OS X

-- escape_string
-- [Colin A. Foster <>, 2004.07.13]

on escape_string(input_string)
	set output_string to ""
	set escapable_characters to " !#^$%&*?()={}[]'`~|;<>\"\\"
	repeat with chr in input_string
		if (escapable_characters contains chr) then
			set output_string to output_string & "\\" -- This actually adds ONE \ to the string.
		else if (chr is equal to "/") then
			set output_string to output_string & ":" -- Swap file system delimiters
		end if
		set output_string to output_string & chr
	end repeat
	return output_string as text
end escape_string