Automator Change to directory of dropped files before running Shell command

applescriptautomatorbashcommand linefolders

Seems extremely simple, but I can't figure it out…

I want to be able to change to the directory (folder) where the dropped file is located before running my shell script on that file.

So either I change to the directory first with Automator, then pass that argument to Shell Script or Applescript

or I change to the directory inside of Applescript or Shell before running my Shell command. pls help

Best Answer

This is very easy in zsh. You can use the :h option to a variable to refer to the head of its full path:

#!/usr/bin/env zsh -f

PATH="/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin"

for i in "$@"
do

    FILE="$i"

    cd "$FILE:h"

    # do other things here

done

In a shell like bash you would need to use the dirname command:

#!/usr/bin/env bash

PATH="/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin"

for i in "$@"
do

    FILE="$i"

    DIR=$(dirname "$FILE")

    cd "$DIR"

    # do other things here

done