Home > other >  Bash/ Automator. How to Loop through directory, change name of files and keep files in directory?
Bash/ Automator. How to Loop through directory, change name of files and keep files in directory?

Time:07-09

Im trying to use Automator to set up a folder action so when a .txt file is dropped into said folder a bash script is run using 'Run Shell Script' I want it loop through the folder and change the names of the files inside.

My settings for this are. Shell : /bin/zsh and Pass input : as arguments and here is my code.

for f in "@$"
do
    mv $f Newfilename.txt
done

I presume the path to the folder is being passed into the script as arguments and is stored in the $@ variable? the path looks something like this '/Users/myname/Desktop/bash_test'

When I drop a .txt file into the folder it changes the name of the file but then moves it to my Users folder, I had expected the files to stay in the folder dictated by the path detailed above.

Would anyone be as kind as to explain why the newly named file moved to my users folder?

and

How can amend this bash script so the newly named file stays in folder the file was dropped in to?

Im using Monterey 12.2.1 and bash 3.2.57

Thanks

CodePudding user response:

mv moves and/or renames files; since you didn't specify what directory to put the file in (just what name to give it), it assumes you mean to put it in the script's working directory (that's pretty much the default anytime you don't specify a specific directory). It just happens that Automator uses your home folder as its working directory, and the shell it starts inherits that.

So, you need to specify to put the file in... the same directory it's in to begin with:

mv -n $f $(dirname $f)/Newfilename.txt

(dirname is a standard command to extract just the enclosing directory from a path -- in this case, $f, which is the path to the file.)

BTW, notice that I added -n to the mv command. That's to keep it from overwriting any file that already exists by that name. Bt default, mv assumes that if there's a name conflict, it should just delete the original file and replace it with the one you told it to move. This has a tendency to cause data loss and regret. mv -n will just not move/rename the file if there'd be a conflict, which is much safer. If you want it to do something else (like add " (2)" to the filename), you'll have to do additional scripting to make that happen.

  • Related