Applescript 根据终端命令的结果执行代码

问题描述 投票:0回答:1

我正在尝试制作一个脚本,让用户可以根据电子表格将许多文件从一个目录复制到其他各个位置。用户不会有确切的文件名,因此脚本需要复制符合条件的所有内容。我认为终端的

ls *[criteria]*
是确定是否有匹配项的最佳方法。

当我尝试使用终端命令的结果时出现问题。这是错误:

"Can’t make «class ttab» 1 of window id 24015 of application \"Terminal\" into type list or string." number -1700 from «class ttab» 1 of window id 24015 to list or string

完整代码如下:

set theSheetAlias to choose file with prompt "Please select the spreadsheet." of type {"public.spreadsheet"}
set theSourceAlias to choose folder with prompt "Please select where to look for photos."
set theSourcePath to quoted form of POSIX path of the theSourceAlias

tell application "Terminal"
    set currentTab to do script ("cd " & theSourcePath)
end tell

tell application "Microsoft Excel"
    activate
    open alias theSheetAlias
    set theSheet to active sheet
    
    -- Loop through each row and move the file to the specified location
    repeat with i from 2 to count of rows of theSheet's used range
        set theStyle to the value of cell 2 of row i of theSheet
        tell application "Terminal"
            set terminalSearch to (do script ("ls *" & theStyle & "*") in currentTab)
            if terminalSearch starts with "zsh: no matches" then
                -- execute some code
            else
                -- execute some other code
            end if
        end tell
    end repeat
end tell
terminal applescript
1个回答
0
投票

我发现我根本不需要涉及终端。我发现我可以将所有这些打包到一个命令中,然后直接作为 shell 脚本运行,而不是打开终端,切换到我想要的目录,然后运行一个命令:

do shell script ("ls " & theSourcePath & "*" & theStyle & "*")

最好的部分是它返回命令的结果,这正是我想要的:

set searchResult to the result

但是如果

ls
没有出现任何结果,它会抛出一个错误。在 shell 中进行错误检查比在 applescript 中进行 try/catch 块更好,所以这是最后的 shell 脚本行:

do shell script ("ls " & theSourcePath & "*" & theStyle & "* || echo \"error\"")

这就是现在的样子。还有很多功能要添加,但是我原来遇到的问题已经完全解决了

set theSheetAlias to choose file with prompt "Please select the spreadsheet." of type {"public.spreadsheet"}
set theSourceAlias to choose folder with prompt "Please select where to look for photos."
set theSourcePath to quoted form of POSIX path of the theSourceAlias


tell application "Microsoft Excel"
    activate
    open alias theSheetAlias
    set theSheet to active sheet
    
    -- Loop through each row and search for any files matching the values in column B
    repeat with i from 2 to count of rows of theSheet's used range
        set theStyle to the value of cell 2 of row i of theSheet
        
        do shell script ("ls " & theSourcePath & "*" & theStyle & "* || echo \"error\"")
        set searchResult to the result
        set resultLines to every paragraph in searchResult
        
        if searchResult is equal to "error" then
            set value of cell 4 of row i of theSheet to "not found"
        else
            set value of cell 4 of row i of theSheet to ((length of resultLines as text) & " files found")
        end if
    end repeat
end tell
© www.soinside.com 2019 - 2024. All rights reserved.