簡體   English   中英

如何將變量FROM applescript傳遞給shell腳本?

[英]How to pass a variable FROM applescript TO a shell script?

我有以下腳本

 #!/bin/bash
 /usr/bin/osascript << EOT
 set myfile to choose file
 EOT

 no_ext=$(python -c "print '$myfile'.split('.')[0]")

 ### this works - just need to know how to pass the arg
 R CMD Sweave no_ext.Rnw
 pdflatex no_ext.tex
 open no_ext.pdf

任何人都可以指向“如何正確傳遞變量myfile”?

為所有建議編輯Thx!

不知道接受什么,所有答案都對我有所幫助,因為我從每個人那里學到了很多東西。

腳本中存在以下問題:

AppleScript部分中設置的變量確實在封閉的shell腳本中定義。 您必須使用命令替換與shell腳本進行數據交換。

從shell腳本調用的AppleScripts不允許進行用戶交互,因為它們沒有應用程序上下文。 您可以使用幫助應用程序“AppleScript Runner”來運行用戶交互命令。

以下是腳本的修訂版本,其中修復了這些問題:

#!/bin/bash

myfile=$(/usr/bin/osascript << EOT
tell app "AppleScript Runner"
    activate
    return posix path of (choose file)
end
EOT)

if [ $? -eq 0 ]
then
    echo $myfile
else
    echo "User canceled"
fi

首先,您需要從Applescript獲取myfile變量的內容為bash。 我不知道Applescript,所以我會在黑暗中拍攝如何寫入其標准輸出。 接着蟒蛇部分只是不必要的復雜性(和可能是錯誤的,無論如何,你是第一個后扔掉一切.而不是最后一次)。 接下來,在bash語法中需要一個$之前的變量名。 我認為以下腳本可以滿足您的需求:

#!/bin/sh
set -e
myfile=$(osascript <<EOT
set myfile to choose file
write myfile to stdout
EOT
)
no_ext="${myfile%.*}"
R CMD Sweave "$no_ext.Rnw"
pdflatex "$no_ext.tex"
open "$no_ext.pdf"

(如果發生錯誤, set -e開頭會立即退出shell,而不是嘗試執行pdflatex即使沒有.tex文件或者某些文件。)

意識到applescript路徑是冒號“:”分隔的。 你需要在bash中使用斜杠分隔,所以在Applecript中這就是“posix路徑”。 此外,使用osascript時無法打開對話框窗口。 您必須告訴應用程序打開窗口。 接下來,你從applecript中“返回”某些內容......這就是bash的內容。 最后,在bash中執行命令並將結果賦值給變量使用``around the command。 所以知道這是一個使用applescript來獲取myFile變量的shell腳本。

#!/bin/bash

myFile=`/usr/bin/osascript << EOT
tell application "Finder"
activate
set myfile to choose file with prompt "Select the file to use in bash!"
end tell
return (posix path of myfile)
EOT`

echo $myFile

暫無
暫無

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

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