Bash – Add extension for multiple files, based on their types

bashrename

I know that there are many questions about adding extension to a multiple files. But none of them could get my job done.

I have a huge list of images without extension, most of them are png, but there are jpg files also and maybe tiff.

How could I rename them correctly?

Best Answer

Perhaps like this:

for f in /some/dir/*; do
    type="$( file -bi -- "$f" )"
    case "${type%%;*}" in
        image/jpeg) ext=jpg ;;
        image/png)  ext=png ;;
        image/tiff) ext=tiff ;;
        *) printf '%s: %s: unknown file type\n' "${0##*/}" "$f" >&2; ext='' ;;
    esac
    if [ -n "$ext" ]; then mv -n -- "$f" "${f}.${ext}"; fi
done
Related Question