运行 bash 删除文件的脚本

Running a bash script on dropped files

我有一个 bash 脚本,如果我通过命令行 运行 它可以按预期工作,但我想通过 Automator Droplet 运行 在删除的文件上使用它.

脚本循环遍历文件并将在“-”之前具有相同子字符串的每个文件放在同一文件夹中。

这是 bash 脚本:

for file in *; do dir=$(echo $file | cut -d- -f1); mkdir -p $dir; mv $file $dir; done

通过终端我可以设置目录并且它可以完美地工作但是通过 Automator 我很难让它工作。 我已经尝试将它包装在一个 Applescript 中,该 Applescript 将丢弃的文件作为输入,但它似乎不起作用,我不太确定它在哪里失败。

on open droppedItems
    repeat with aFile in theFiles
        do shell script "do dir=$(echo $file | cut -d- -f1); mkdir -p $dir; mv $file $dir; done"
    end repeat
end open

我也试过这个,虽然我应该让你接受参数并生成一个列表来执行命令。

for arg in [list]; do dir=$(echo $file | cut -d- -f1); mkdir -p $dir; mv $file $dir; done

这就是我为 运行 shell 脚本 编写代码的方式] Shell Script action with Pass input: [as arguments] in the Automator workflow 用作 Service/Quick Action1:

示例 shell 脚本 代码:

    # f  = fully qualified pathname
    # d  = directory pathname
    # fn = filename with extension
    # dn = portion of filename up to - and
    #      the dir to create, if necessary.

for f in "$@"; do
    [ -f "${f}" ] || continue
    d="${f%/*}"
    fn="${f##*/}"
    dn="${fn%-*}"
    cd "${d}" || exit
    [ ! -d "${dn}" ] && mkdir "${dn}"
    mv -n "${f}" "${dn}"
done



备注:

  • -n选项用于mv命令停止覆盖现有的文件。如果您有想要覆盖现有 文件 的情况,请删除 mv -n 选项 命令.
  • 1 示例 shell 脚本 代码 也可以在 Automator workflow 中用作 application for dragdrop 操作。只需 select Application 创建新的 workflow 并添加 运行 Shell脚本 action with Pass input: [as arguments] and the code.