Script to rename files using the sha1 () hash of their file name

I am creating a website and I would like the hash file names of my images.

How to create a bash script file that renames every file in a directory using sha1 old file name?

I tried:

#!/bin/bash for file in * do if [ -f "$file" ];then newfile="openssl sha1 $file" mv "$file" $newfile" fi done 

But this does not work :(

EDIT

Based on the suggestions here, I tried this:

 #!/bin/bash for file in old_names/* do if [ -f "$file" ];then newfile=$(openssl sha1 $file | awk '{print $2}') cp $file new_names/$newfile.png fi done 

This renames the files, but I'm not sure what was used to hash the file name. Has the expansion increased? made a way?

INFO

Then I will use the PHP sha1 () function to display the images:

 echo "<img src=\"images/".sha1("$nbra-$nbrb-".SECRET_KEY).".png\" />\n"; 
+7
source share
4 answers

The code examples in the answers so far and in your editing haveh the contents of the file. If you want to create file names that are hashes of the previous file name, not including the path or extension, do the following:

 #!/bin/bash for file in old_names/* do if [ -f "$file" ] then base=${file##*/} noext=${base%.*} newfile=$(printf '%s' "$noext" | openssl sha1) cp "$file" "new_names/$newfile.png" fi done 
+6
source

Try the following:

 newfile=$(openssl sha1 $file | awk '{print $2}') mv $file $newfile 
+2
source

I tried to do the same, but the fragments here were not / exactly / what I needed, plus I'm new to bash scripts ... sorry ... I ended up getting some ideas stuck with a script that does what I need - look at the files in. / pics and rename them to your old hash, while maintaining the current extension. I checked this with a bunch of different photos, and it still works as intended. I guess another novice like me could copy / paste this and be nice if your end result is the same as mine. Thank you all for your help!

 #!/bin/bash for file in ./pics/* do newfile=$(openssl sha1 $file | awk '{print $2}') ext=${file##*.} mv "$file" "./pics/$newfile"."$ext" done 
+1
source

try

 newfile=$(openssl sha1 $file) mv "$file" "${newfile##*= }" 
0
source

All Articles