使用苹果的 Automator 将文件名传递给一个 shell 脚本

17

我有一个 Automator 脚本,想要在一个文件夹上运行。我希望这个脚本能够对文件夹中的每个文件执行我的 shell 命令。虽然 Automator 已经设置为将输入传递给标准输入(stdin),但我认为下面的使用方式不正确,请帮助我。

for f in "$@" 
do
    java -Xmx1000m -jar /Users/myprog/myprog.jar $f 
done
4个回答

14

你所说的“没有正确使用stdin”是正确的。事实上,根据你提供的脚本片段,你的脚本假定你正在从命令行获取文件作为参数...你根本没有使用stdin!

在运行Shell脚本操作的右上角,X下面有一个下拉框,包括两个选项:“将输入传递到stdin”和“将输入作为参数传递”。这些选项决定如何将所选文件传递给您的脚本操作。如果选择了“作为参数”选项,则您的脚本应该使用以下模板:

for f in "$@"; do
# so stuff here
done

当选择“作为参数”选项时,此模板由操作本身提供。

另一方面,如果选择了“输入到stdin”选项,则您的脚本应使用此模板:

while read fname; do  # read each line - assumes one file name per line
   # do clever stuff with the filename
   echo $fname # to illustrate we'll simply copy the filename to stdout
done

(如果您不知道Bash脚本编程,则#之后的所有内容都是注释)

请注意,由脚本操作提供的模板仅为简单的单个命令。

cat

我认为这并不是很有帮助。

请注意,直到您实际输入文本到脚本区域中,切换“到stdin”和“作为参数”的选项将更改脚本框的内容(我假设这是提示您脚本应该是什么样子),但一旦您输入了东西,切换就不再发生。


10
特殊变量$@表示提供给脚本的所有命令行参数。 for循环遍历每个参数,并在每次执行jar文件。您可以将脚本缩短为:
for f
do
    java -Xmx1000m -jar /Users/myprog/myprog.jar "$f"
done

因为 for 的默认行为是使用 $@

如果参数中存在空格,你应该在 java 命令的结尾处加上引号来包含 $f。


7
根据我在这里看到的,您可以设置一个便捷的“服务”,允许您通过Finder上下文菜单右键单击并转换文件。
设置步骤如下:
  • Launch Automator
  • From the main menu choose "New"
  • Select "Service" (the gear icon)
  • Drag and drop "Utilities -> Run Shell Script" from the left-hand library into the main "editor" area.
  • Replace the existing text "cat" with the following code:

    for f in "$@"; do
        /usr/bin/afconvert -f caff -d LEI16@32000 -c 1 --mix "$f"
        echo "$f converted"
    done
    

    NOTE: The setup above will convert to mono (-c 1 --mix) at 16 bit @ 32000hz (LEI16@32000 = little endian 16 bit). Use /usr/bin/afconvert -h in terminal to see all of the available options.

  • At the top of the editor you should see two drop downs, set them as follows:

    Service receives selected [Files and Folders] in [Finder.app]
    
  • In the Shell Script editor area, ensure:

    "Shell" is set to "/bin/bash"
    

    and

    "pass input" is set to "arguments" 
    
  • Save the thing something like "Convert to CAF"

  • Navigate to a folder with some WAVs in there.
  • Right click on a WAV and you should see "Convert to CAF" at the bottom of the contextual menu.

2
我不确定我是否理解您的问题,因为您的脚本似乎没有使用stdin。$@特殊参数将在argv中扩展为传递的位置参数。它的工作方式与您直接从shell调用脚本的方式相同:请参考$@特殊参数
$ cat >test
for f in "$@"
do
  echo $f
done
$ chmod 755 test
$ ./test a b c
a
b
c

如果你想从标准输入中获取参数,你可以像这样操作:
$ cat >test2
for f in $(cat)
do
  echo $f
done
$ chmod 755 test2
$ ./test2 <<EOF
> a b c
> EOF
a
b
c

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接