Skip to content

Instantly share code, notes, and snippets.

@teknikqa
Created December 4, 2016 13:13
Show Gist options
  • Save teknikqa/432e0a1ca10599142616948844afbfaf to your computer and use it in GitHub Desktop.
Save teknikqa/432e0a1ca10599142616948844afbfaf to your computer and use it in GitHub Desktop.
Categorize files into sub-directories based on their file type.
#!/bin/bash
die () {
echo -e "\033[0;31m$*\033[m" >&2
exit 1
}
DIR=${1:-.}
if [ ! -d "$DIR" ]; then
die "Not a valid dir!"
fi
for file in "$DIR"/* ; do
if [ -f "$file" ]; then
mime=$(file -ib "$file" | cut -f1 -d ';')
if [ ! -d "$DIR/$mime" ]; then
mkdir -p "$DIR/$mime" || die "Couldn't make the directory $mime. Check if it already exists!"
fi
mv "$file" "$DIR/$mime" || die "Moving the file $file to directory $mime failed!"
elif [ -d "$file" ]; then
echo "Skipping a directory $file"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment