将bash命令返回的路径名分配给AppleScript列表 [英] Assign pathnames returned from bash command(s) to an AppleScript list
问题描述
我想在Applescript中以列表的方式(递归)提示最近添加的10个文件路径.在bash中可以正常工作:
I want to prompt the paths of the 10 recently added files of a directory (recursively) in Applescript as a list. This works fine in bash:
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
array=(`find . -type f -print0 | xargs -0 ls -t | head -n 10`)
echo "${array[*]}"
IFS=$SAVEIFS
我想将结果数组存储在Applescript变量中:
I’d like to store the resulting array in an Applescript Variable:
set l to (do shell script "______________")
如何将bash零件放入可以工作的1-liner?也许还有仅Applescript的解决方案?
How can I put the bash part into a working 1-liner? Maybe there is also an Applescript-only solution?
推荐答案
从AppleScript中掏空" 时,您为变量分配的值的 class
,(在您的示例中,名为 l
的变量)将始终为列表
When you "shell out" from AppleScript the class
of the value that you assign to a variable, (i.e. the variable named l
in your example), will always be text and not a list.
在您的方案中,您实际上是在捕获找到实用程序的路径名等发送到Applescript只是识别为 text
的 stdout
(fd 1).
In your scenario you're essentially capturing the pathname(s) that the find utility etc send to stdout
(fd 1) which Applescript just recognizes as text
.
要转换每行(即通过bash命令打印为 stdout
的路径名),您需要使用帮助程序
To convert each line (i.e. a pathname that is printed to stdout
via your bash commands) you'll need to utilize a helper subroutine/function as shown in the following gist.
set stdout to do shell script "/usr/bin/find " & quoted form of "/absolute/path/to/target/directory" & " -type f -print0 | xargs -0 ls -t | head -n 10"
set latestList to transformStdoutToList(stdout)
-- Test it's a proper AppleScript list.
log class of latestList
log (item 1 of latestList)
log (item 2 of latestList)
-- ...
(**
* Transforms each line printed to stdout to form a new list of pathnames.
*
* Pathname(s) may contain newline `\n` characters in any part, including
* their basenames. Below we read each line, if it begins with a forward
* slash `/` it is considered to be the start of a pathname. If a line does
* not begin with a forward slash `/` it is considered to be part of the
* prevous pathname. In this scenario the line is appended to previous item
* of the list and the newline character `\n` is reinstated.
*
* @param {String} pathsString - The pathname(s) printed to stdout.
* @return {List} - A list whereby each item is a pathname.
*)
on transformStdoutToList(pathsString)
set pathList to {}
repeat with aLine in paragraphs of pathsString
if aLine starts with "/" then
set end of pathList to aLine
else
set last item of pathList to last item of pathList & "\n" & aLine
end if
end repeat
return pathList
end transformStdoutToList
说明:
-
在第一行中阅读:
In the first line reading:
set stdout to do shell script "/usr/bin/find " & quoted form of "/absolute/path/to/target/directory" & " -type f -print0 | xargs -0 ls -t | head -n 10"