Search code examples
shellfor-loopapplescriptrepeatosascript

Can't do shell script with a repeat with i from 1 to n loop


This works (prints, for example, “3 arguments”):

to run argv
    do shell script "echo " & (count argv) & " arguments"
end run

This doesn't (prints only “Argument 3: three”, and not the previous two arguments):

to run argv
    do shell script "echo " & (count argv) & " arguments"

    repeat with i from 1 to (count argv)
        do shell script "echo 'Argument " & i & ": " & (item i of argv) & "'"
    end repeat
end run

In both cases, I'm running the script using osascript on Mac OS X 10.5.5. Example invocation:

osascript 'Script that takes arguments.applescript' Test argument three

I'm not redirecting the output, so I know that the script is not throwing an error.

If I add a display dialog statement above the do shell script, it throws a “no user interaction allowed” error, so I know that it is executing the loop body.

What am I doing wrong? What is it about this loop that causes osascript to not print anything?


Solution

  • Try this to avoid having to use the temporary file.

    to run argv
            set accumulator to do shell script "echo " & (count argv) & " arguments" altering line endings false
            repeat with i from 1 to (count argv)
                    set ln to do shell script "echo 'Argument " & i & ": " & (item i of argv) & "'" altering line endings false
                    set accumulator to accumulator & ln
            end repeat
            return accumulator
    end run