簡體   English   中英

osascript如何傳入變量

[英]osascript how to pass in a variable

我有以下,不工作。 它在終端中打開了一個新選項卡,但變量 $DomainName 沒有傳入?

DomainName="example.com"
osascript -e 'tell application "Terminal" to do script "watch dig +short NS $DomainName"'

結果是:

watch dig +short NS $DomainName

你如何傳遞一個變量?

OP 的問題是在調用osascript時如何[不] 清理 shell 腳本輸入的大師班。

這是危險的不安全:

foo="DO NOT DO THIS; say bad script"
osascript -e "tell application \"Terminal\" to do script \"echo $foo\""

(運行該示例以了解我的意思,然后考慮不太友好的字符串會造成什么后果。)

將變量$foo雙引號作為"$foo"可以安全地通過頂級 shell 腳本。 不能安全地通過 AppleScript:

foo="say \"bad script\""
osascript -e "tell application \"Terminal\" to do script \"echo $foo\""

如果您運行該示例,它將失敗並出現 AppleScript 編譯錯誤:標識符不能在此“”之后 go。(-2740)

那是因為osascript接收字符串:

tell application "Terminal" to do script "echo say "bad script""

這是無效的語法。 (嘗試在腳本編輯器中編譯該行以查看。)

通過 AppleScript arguments 的正確方法是將它們附加到osascript的 arguments 列表:

osascript -ss -e "…" - "arg1" "arg2" "arg3"

需要-分隔符將命令自己的選項列表與剩余的 arguments 分開以轉發到 AppleScript 的run處理程序。

順便說一句,通過osascript的標准輸入而不是-e選項傳遞 AppleScript 也是一個好主意,因為這樣您就可以編寫普通的 AppleScript 代碼而不必轉義它:

osascript -ss - "arg1" "arg2" "arg3" <<EOF

    on run argv -- argv is a list of 3 strings
        argv -- do stuff with argv here
    end run

EOF

(您可以安全地運行該示例:它只是將argv的值寫入標准輸出。)

好的,就將 arguments 傳遞給 AppleScript 而言,這是安全的。

..

但是,OP 的 AppleScript 創建了一個新的 shell 腳本以在 Terminal.app 中運行。 因此,必須清理用於構造 shell 腳本的 AppleScript 字符串,這是使用 AppleScript 的quoted form of STRING完成的。

因此,這是通過所有三個級別的代碼生成來清理任意字符串的正確安全方法:

bar='$test" \t#est*;say bad script' # a proper nasty test string

osascript -  "$bar"  <<EOF

    on run argv -- argv is a list of strings
        tell application "Terminal"
            do script ("echo " & quoted form of item 1 of argv)
        end tell
    end run

EOF

運行該示例,我在這里使用的相當可怕的測試字符串一直安全地傳遞到echo

是的,所有這些字符串清理/代碼生成的東西讓人頭疼,但這就是你使用這么多由瘋狂的人設計的語言所得到的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM