2013-06-21 205 views
11

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

如何从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 

回答

13

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 

而你c里面一个免费的编写多的脚本,它比使用多个-e ARGS好得多......

+0

这是个不好的建议。除了不必要的笨拙之外,它不会消除插入的文本,因此既不健壮也不安全,例如, 'text ='Bob说“hello”''会导致AS由于未转义的引号而引发语法错误。如果存在更好的解决方案,切勿使用代码管理:如Lauri Ranta所说,定义一个明确的“运行”处理程序并通过ARGV传递您的字符串。有关更多详细信息,请参阅http://stackoverflow.com/questions/16966117/bash-combining-variables-to-form-a-command-sent-to-applescript-using-the-osascr/16977401#16977401。 – foo

+1

@foo您说得对,在运行argv时使用“更正确”。我并不是一个完美的解决方案,但我很多次都没有任何问题地使用它,它很简单,可用于许多脚本... – jm666

+1

你是一个_buggy_解决方案。如果$ text包含双引号或反斜线字符,则会导致AS代码出错或者更糟糕 - 以非预期方式运行。如果你必须使用代码管理,你必须清理你的输入。例如谷歌的“SQL注入攻击”,理解为什么“它对我有用”,当某人指出这个缺陷时,并不是一个适当的回应。 – foo

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。

相关问题