Reputation: 13
I have a bash script that works as intended if I run it through the command line but I would like to have it run on dropped files files via an Automator Droplet.
The script loops through the files and places every file that has the same substring before the "-" in the same folder.
Here is the bash script:
for file in *; do dir=$(echo $file | cut -d- -f1); mkdir -p $dir; mv $file $dir; done
Through the Terminal I can set the directory and it works flawlessly but going through Automator I am having a hard time getting it to work. I have tried wrapping it inside an Applescript that takes dropped files as an input but it does not seem to work and I'm not quite sure where it is failing.
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
I also tried this which I though was supposed to let you take the arguments and generate a list on which to execute the commands.
for arg in [list]; do dir=$(echo $file | cut -d- -f1); mkdir -p $dir; mv $file $dir; done
Upvotes: 1
Views: 1247
Reputation: 7555
This is how I'd code the shell script for the Run Shell Script action with Pass input: [as arguments] in the Automator workflow used as a Service/Quick Action1:
Example shell script code:
# 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
Notes:
-n
option used in the mv
command stops from overwriting an existing file. If you have a scenario where you want existing files overwritten, then remove the -n
option used in the mv
command.Upvotes: 3