Read "command" from text file, do shell script "command"?

I am trying to write an Applescript that reads a command-line from a text file and then runs “do shell script” to perform the command. I’ve read Apple’s technical notes, but I can’t the script to perform the command.

Here is a brief version:

set openCmd to open for access POSIX file "/Users/myname/HOSTCMD.TMP"
set cmdLine to (read openCmd for (get eof openCmd))
close access openCmd
do shell script cmdLine
--or: do shell script quoted form of cmdLine

The contents of HOSTCMD.TMP are (for example)


or similar commands that work in Terminal. None of them work in this script

The commands work perfectly if I use:

do shell script "open -a Safari"

But not when I read the command from a file.

The text file, incidentally, is created by an MS-DOS application, but I have the same problem if it’s created by Textedit.

I am probably missing something obvious, but I can’t guess what it is. Any help will be gratefully received.


Your script works fine here with a test file. What kind of text does your file contain? One way to find out is:

-- 'open for access' and 'close access' aren't needed for a one-off read.
characters of (read POSIX file "/Users/myname/HOSTCMD.TMP")

If the result’s {“o”, “p”, “e”, “n”, " ", “-”, “a”, " ", “/”, “A”, “p”, “p”, “l”, “i”, “c”, “a”, “t”, “i”, “o”, “n”, “s”, “/”, “S”, “a”, “f”, “a”, “r”, “i”, “.”, “a”, “p”, “p”}, your script should work. If every alternate character is an empty string, your file contains Unicode text and will have to be read as such. If it’s formatted text, it’ll have to be read by an application which understands the formatting.


Thank you. My text file is in fact plain text, not unicode text. The problem seems to occur because my text file is created by an MS-DOS application. If I run

in an MS-DOS emulator, the file has one more byte than the file created if I run the command in the OS X command shell. Presumably there is a CR/LF at the end, not just an LF, but I will need to look into this.

I will try using the unix “tr” command to convert the MS-DOS file into unix format and see if that helps. Thank you for showing me that the problem was not in the script itself!

Yes, the problem was that I was creating the file in MS-DOS, and the CR/LF pair was presumably causing the problem. I fixed it with this:

do shell script "perl -pi -e 's/\\r\\n/\\n/g' /Users/myname/HOSTCMD.TMP"

Thank you again!