Created
November 16, 2012 16:15
-
-
Save larvanitis/4088616 to your computer and use it in GitHub Desktop.
BASH::Filter file on mimetype
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# make sure the file exists and that it's a regular file before proceeding | |
[ -z "$1" ] && echo "you must specify a file!" >&2 && exit 1 | |
[ ! -e "$1" ] && echo "$1 doesn't exist!" >&2 && exit 1 | |
[ ! -f "$1" ] && echo "$1 is not a regular file!" >&2 && exit 1 | |
FILE=$1 | |
FILE_MIME=$(file -b --mime-type "$FILE") #or "xdg-mime query filetype" | |
VALID_MIMETYPES=( | |
"application/octet-stream" #bmp image | |
"application/pdf" #pdf | |
"application/postscript" #ps | |
"image/jpeg" #jpg image | |
"image/png" #png image | |
"image/tiff" #tiff image | |
"text/plain" #text file | |
) | |
# searches for an element in the specified array and | |
# returns 0 if found, otherwise 1 | |
# $1 is the element to search for | |
# $2 is the array | |
# source: patrik at http://stackoverflow.com/a/8574392 | |
containsElement () { | |
local e | |
for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done | |
return 1 | |
} | |
if containsElement "$FILE_MIME" "${VALID_MIMETYPES[@]}" | |
then | |
echo "do something with valid file" | |
else | |
echo "do something with invalid file" | |
fi |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
FILE=$1 | |
MIMETYPES=( | |
"application/octet-stream" #bmp image | |
"application/pdf" #pdf | |
"application/postscript" #ps | |
"image/jpeg" #jpg image | |
"image/png" #png image | |
"image/tiff" #tiff image | |
"text/plain" #text file | |
) | |
#for more specific mimetype lookups see "xdg-mime query filetype" | |
getMimetype () { | |
file -b --mime-type $1 | |
} | |
# searches for an element in the specified array and | |
# returns 0 if found, otherwise 1 | |
# $1 is the element to search for | |
# $2 is the array | |
# source: patrik at http://stackoverflow.com/a/8574392 | |
containsElement () { | |
local e | |
for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done | |
return 1 | |
} | |
if [ -e "$FILE" ] | |
then | |
if [ -f "$FILE" ] && containsElement $(getMimetype "$FILE") "${MIMETYPES[@]}" | |
then | |
echo "do something with valid file" | |
else | |
echo "do something with invalid file or dir" | |
fi | |
else | |
echo "$FILE doesn't exist!" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment