How can I test whether a variable has a valid video file extension (.mp4) ?
1 Answers
Using a shell pattern comparison in e.g. bash:
if [[ $variable == *.mp4 ]]; then
printf 'String "%s" ends in ".mp4"\n' "$variable"
else
printf 'String "%s" has some other suffix\n' "$variable"
fi
or, using a standard case statement, which may be prettier if you want to compare many suffix strings,
case $variable in
*.mp4)
printf 'String "%s" ends in ".mp4"\n' "$variable"
;;
*.mov)
printf 'String "%s" ends in ".mov"\n' "$variable"
;;
*.blarg|*.foo)
printf 'String "%s" ends in ".blarg" or ".foo"\n' "$variable"
;;
*)
printf 'String "%s" has some other suffix\n' "$variable"
esac
If your variable contains a pathname and you want to test whether the file at that pathname is a file in a video format, it would (possibly) be better to ask the file command to classify the file's contents. This is because files on Unix systems are arbitrary, and a directory may be called my video.mp4 even though it's clearly not a video file.
You can get the MIME-type of a file using file -i (here, I'm also using file with its -b option for "brief" output, without the filename):
$ file -b -i 'video/the_amazing_spiderman_trailer.mp4'
video/mp4; charset=binary
This could be used in a script:
if file -b -i "$variable" | grep -q -F 'video/mp4;'
then
printf '"%s" is most likely an MP4 video\n' "$variable"
fi
In the code above, it does not matter what suffix string $variable contains.
Note that I'm testing this on a FreeBSD system and that the output of file is not standard. You need to test on your local machine. Also note that the file command on macOS uses -I in place of -i.
A somewhat related question with more info about file in my answer to it:
- 333,661
file --mime-type -b file.mp4– Edgar Magallon Jan 27 '23 at 09:52