2013-06-21 203 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。

相關問題