I’m trying to check the type of a file using file, and then using the cut command to get only the type such as JPEG in my case, and then using it to check whether or not the file is the desired type. However whenever I run this in Shell it spits out pic1.jpg: Unexpected Operator. I’m not sure where the problem is and it’s been boggling me for a while now.
!#/bin/sh
file=$(file -F " " $1)
if [ $file = ERROR: ] || [ $file = empty ] then
echo "$1 is not a valid jpeg file." >&2 >> error.log
else
extension=$(file -F " " $1 | cut -f 3 -d " ")
Note that you’ll have to enclose
$filein double quotes in theifstatement. Otherwise the contents of$filewill be interpreted as commands by the shell. This is one of the major pitfalls of shell coding you should be aware of.In addition you where missing the
;between the]and thethenstatements. Note that[ ... ]is the same as thetestcommand.]is just the last argument to it. Not ‘just a bracket’ like you would expect in ‘normal languages’ :). So, if there are two expressions on the same line the will have to be separated by an;Although I could suggest some enhancements to the I kept my example as much the same as yours to point you to the error. The following code will work:
Note that without double quotes your script would lead to the following if statement: