I'm building a website and I would like to hash the filenames of my images.
How can I create a bash script file that renames every file in a directory with the sha1 of the old filename ?
I've tried :
#!/bin/bash
for file in *
do
if [ -f "$file" ];then
newfile="openssl sha1 $file"
mv "$file" $newfile"
fi
done
But that doesn't work :(
EDIT
Based on 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 does rename the files, but I'm not sure what has been used to hash the file name. Did the extention get hashed ? did the path ?
INFO
I will then use PHP's sha1() function to display the images :
echo "<img src=\"images/".sha1("$nbra-$nbrb-".SECRET_KEY).".png\" />\n";
The code examples in the answers so far and in your edit hash the contents of the file. If you want to create filenames that are hashes of the previous filename, not including the path or extension, then do this:
#!/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