bash 意外标记“if”附近的语法错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14541501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
syntax error near unexpected token `if'
提问by el HO
I am currently trying to write a bash script which helps me step through a directory and check for .jpeg or .jpg extensions on files. I've come up with the following:
我目前正在尝试编写一个 bash 脚本,它可以帮助我遍历目录并检查文件上的 .jpeg 或 .jpg 扩展名。我想出了以下几点:
#declare $PICPATH, etc...
for file in $PICPATH
if [ ${file -5} == ".jpeg" -o ${file -4} == ".jpg" ];
then
#do some exif related stuff here.
else
#throw some errors
fi
done
Upon execution, bash keeps throwing a an error on the if line: "syntax error near unexpected token `if'.
执行时,bash 不断在 if 行抛出错误:“意外标记‘if’附近的语法错误。
I'm a completely new to scripting; what is wrong with my if statement?
我完全不熟悉脚本;我的 if 语句有什么问题?
Thanks.
谢谢。
回答by cyfur01
I think you're just missing the do clause of the forloop:
我认为您只是缺少for循环的 do 子句:
#declare $PICPATH, etc...
for file in $PICPATH; do
if [ ${file -5} == ".jpeg" -o ${file -4} == ".jpg" ];
then
#do some exif related stuff here.
else
#throw some errors
fi
done
回答by Gilles Quenot
${file -5}
is a syntax error. Maybe you mean
是语法错误。也许你的意思是
${file#*.}
?
?
Anyway, better do :
无论如何,最好这样做:
for file in $PICPATH; do
image_type="$(file -i "$file" | awk '{print gensub(";", "", )}')"
case $image_type in
image/jpeg)
# do something with jpg "$file"
;;
image/png)
# do something with png "$file"
;;
*)
echo >&2 "not implemented $image_type type "
exit 1
;;
esac
done
If you only want to treat jpgfiles, do :
如果您只想处理jpg文件,请执行以下操作:
for file in $PICPATH; do
image_type="$(file -i "$file" | awk '{print gensub(";", "", )}')"
if [[ $image_type == image/jpeg ]]; then
# do something with jpg "$file"
fi
done

