for file in ~/path/to/images/*; do
TYPE=$(file --mime-type -b "$file" | cut -f2 -d/);
if [[ ! $file =~ \.$TYPE ]]; then
echo mv -v "$file" "$file.$TYPE";
TYPE=$(file --mime-type -b "$file" | cut -f2 -d/); (finding file type)
find the extension of each
file(determine file type) command.
--mime-type, --mime-encoding option used for print only the specified element(s).
-b, --brief option used for do not prepend filenames to output lines (brief mode).
See also man file for more info.
Now we extracted the file type and saved it into
And what is
cut -f2 -d/ command? This used for printing just extension type, Like
image/png output from
file --mime-type -b "$file" result.
-f2 prints second part with
-d option) between fields. ex: Print
See also man cut for more info.
if [[...]]; (checking file extension)
We skipped all existing extension with a simple regex, using the
=~ operator inside a
[[...]] test in if condition:
if [[ $file =~ \.$TYPE ]];
$file is your images filenames and
$TYPE is its extension which we found and stored that into
TYPE variable in
TYPE=$(file --mime-type -b "$file" | cut -f2 -d/);.
Then we skip to rename all files that has an extension with themselves.
! refer to: if file has NO extension with itself, then rename that and add its extension at the end of its name.
echo mv -v "$file" "$file.$TYPE";(rename step)
In this line Actually we are appending the file extension(if
$file doesn't an extension with itself) at the end of
$file file by using
mv also using for renaming Files/Directory.
Then we rename
$file.$TYPE. For example file
1 will be rename to
1.png if its file type was
in theory actually above mv command do this: rename filename -> filename.filetype
That filename stored into
$file variable and filetype stored into
How can you use this script?
Copy and paste the script in
gedit and save it with your favorite name ex:
batchRename, then open Terminal and run it by the following command:
DON'T forget before running script verify your correct images path
/path/to/images/ and for renaming on your files after checking the result with
echo command, remove
echo from the beginning
echo mv -v "$file" "$file.$TYPE" and run the script again and enjoy renaming ;)