代码之家  ›  专栏  ›  技术社区  ›  Peter Hosey

无法使用i从1到n循环重复执行shell脚本

  •  3
  • Peter Hosey  · 技术社区  · 18 年前

    这是可行的(例如,打印3个参数):

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

    这不会(仅打印参数3:3,而不是前两个参数):

    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
    

    在这两种情况下,我都使用 osascript 在Mac OS X 10.5.5上。调用示例:

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

    我没有重定向输出,因此我知道脚本没有抛出错误。

    如果我加上 display dialog 上述声明 do shell script ,它抛出一个不允许用户交互的错误,因此我知道它正在执行循环体。

    2 回复  |  直到 18 年前
        1
  •  2
  •   tvanfosson    18 年前

    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
    
        2
  •  0
  •   Community Mohan Dere    6 年前

    您的问题似乎与循环或argv的使用无关。这里有一个更简单的测试用例,其中只有最后一个 do shell script 实际返回一个结果:

    do shell script "echo foo"
    delay 2
    do shell script "echo bar"
    

    to run argv
        do shell script "echo " & (count argv) & " arguments > /test.txt"
        
        repeat with i from 1 to (count argv)
            do shell script "echo 'Argument " & i & ": " & (item i of argv) & "' >> /test.txt"
        end repeat
    end run
    

    test.txt

    3 arguments
    Argument 1: foo
    Argument 2: bar
    Argument 3: baz
    

    此解决方案失败:

    to run argv
        do shell script "echo " & (count argv) & " arguments > /tmp/foo.txt"
        
        repeat with i from 1 to (count argv)
            do shell script "echo 'Argument " & i & ": " & (item i of argv) & "' >> /tmp/foo.txt"
        end repeat
        
        do shell script "cat /tmp/foo.txt"
        do shell script "rm /tmp/foo.txt"
    end run
    

    即使现在,也只返回最后一行。这可能与以下问题有关: TN2065 :

    问:我的脚本将在很长一段时间内产生输出。当结果出来时,我如何阅读?

    唉,我没有足够的AppleScript fu来知道如何让AppleScript本身读取多行,我怀疑这会起作用。