简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM