My third post on Bash scripting. This time I used a loop in the script. It’s still a simple script but also a very useful one. I regularly import photos from my digital camera or from my smartphone. The file names of these photos are either a number or a random string of characters. I like to rename these photos to give them a more meaningful name for instance summer2018.
The script lets me choose a folder and next asks for a file name. Then the script determines whether the folder exists and if it does it copies all .jpg files and gives the copied files a new name and a number starting with 0 and increasing the number with one for every photo in the folder. The files are copied so the old files still exists just in case a mistake was made. If I’m satisfied I delete the original files manually.
Question: I’d rather have a file name number with three decimals starting from 000 but I haven’t got I clue how to do that. Any ideas?
If you want to use this script, copy the code below and paste it into an editor like vim, vi or Geany. Save it e.g under the name rename and make this file executable by typing.
chmod 755 rename
To run the script just type.
1 #!/bin/bash 2 # written by Eric Buijs 29 januari 2019 3 # rename changes all the jpg files in a user specified folder 4 5 counter=0 6 7 read -p 'type the name of the folder here (e.g: /Users/myname/Documents): ' dname 8 9 read -p 'type the new name of the files (without extension): ' fname 10 11 if [ -d $dname ] 12 then 13 echo directory exists 14 cd $dname 15 echo $dname 16 files=$dname/*.jpg 17 for file in $files 18 do 19 cp $file $dname/$fname$counter.jpg 20 ((counter++)) 21 done 22 else 23 echo directory does not exist 24 fi 25 26 echo 'All done'