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 rena开发者_开发技巧mes 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
Try this:
newfile=$(openssl sha1 $file | awk '{print $2}')
mv $file $newfile
I was trying to do the same sorta thing but the snippets here weren't /exactly/ what I needed, plus I'm brand new to bash scripting... sorry... In the end I stuck several ideas together into the script that does what I need which is -- look at the files in ./pics and rename them to their old hash while maintaining the current extension. I've tested this on a bunch of different pictures and so far it works as intended. I imagine another newbie such as myself would be able to copy/paste this in and be good to go if your end result happens to be the same as mine. Thanks everyone for the help!
#!/bin/bash
for file in ./pics/*
do
newfile=$(openssl sha1 $file | awk '{print $2}')
ext=${file##*.}
mv "$file" "./pics/$newfile"."$ext"
done
try
newfile=$(openssl sha1 $file)
mv "$file" "${newfile##*= }"
精彩评论