【问题标题】:Pass in variable from shell script to applescript将变量从 shell 脚本传递到 applescript
【发布时间】:2013-06-21 19:19:40
【问题描述】:

我有一个使用osascript 调用的shell 脚本,而osascript 调用一个shell 脚本并传入一个我在原始shell 脚本中设置的变量。我不知道如何将该变量从 applescript 传递到 shell 脚本。

如何将变量从 shell 脚本传递到 applescript 到 shell 脚本...?

如果我不明白,请告诉我。

 i=0
 for line in $(system_profiler SPUSBDataType | sed -n -e '/iPad/,/Serial/p' -e '/iPhone/,/Serial/p' | grep "Serial Number:" | awk -F ": " '{print $2}'); do
 UDID=${line}
 echo $UDID
 #i=$(($i+1))
 sleep 1


 osascript -e 'tell application "Terminal" to activate' \
 -e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down' \
 -e 'tell application "Terminal" to do script "cd '$current_dir'" in selected tab of the front window' \
 -e 'tell application "Terminal" to do script "./script.sh ip_address '${#UDID}' &" in selected tab of the front window'

 done

【问题讨论】:

    标签: bash shell applescript osascript


    【解决方案1】:

    Shell 变量不会在单引号内展开。当您想将 shell 变量传递给 osascript 时,您需要使用双 "" 引号。问题是,您必须转义 osascript 中所需的双引号,例如:

    脚本

    say "Hello" using "Alex"
    

    你需要转义引号

    text="Hello"
    osascript -e "say \"$text\" using \"Alex\""
    

    这不是很可读,因此最好使用 bash 的 heredoc 功能,比如

    text="Hello world"
    osascript <<EOF
    say "$text" using "Alex"
    EOF
    

    而且你可以在里面免费写多行脚本,比使用多个-e args 好多了...

    【讨论】:

    • 这是个坏建议。除了不必要的笨拙之外,它不会清理插入的文本,因此既不健壮也不安全,例如text='Bob says "hello"' 将导致 AS 由于未转义的引号而引发语法错误。如果存在更好的解决方案,永远不要使用代码修改,它确实如此:正如 Lauri Ranta 所说,定义一个显式的 run 处理程序并通过 ARGV 传递你的字符串。请参阅*.com/questions/16966117/… 了解更多详情。
    • @foo 你是对的,使用on run argv 是“更多”正确的。我的不是一个完美的解决方案,但我自己使用了很多次没有任何问题,它简单且可用于许多脚本...
    • 你的解决方案是 buggy。如果 $text 包含双引号或反斜杠字符,它将导致 AS 代码出错,或者 - 更糟 - 以意想不到的方式表现。如果你必须使用代码修改,你必须清理你的输入。例如谷歌“SQL 注入攻击”以了解为什么“它对我有用”在有人指出此缺陷时是一个适当的回应。
    【解决方案2】:

    您还可以使用运行处理程序或导出:

    osascript -e 'on run argv
        item 1 of argv
    end run' aa
    
    osascript -e 'on run argv
        item 1 of argv
    end run' -- -aa
    
    osascript - -aa <<'END' 2> /dev/null
    on run {a}
        a
    end run
    END
    
    export v=1
    osascript -e 'system attribute "v"'
    

    我不知道任何获取 STDIN 的方法。 on run {input, arguments} 仅适用于 Automator。

    【讨论】: