在 bash 中检查文件扩展名的最简单方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18278990/
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
Easiest way to check for file extension in bash?
提问by Liam
I have a shell script where I need to do one command if a file is zipped (ends in .gz) and another if it is not. I'm not really sure how to approach this, here's an outline of what I'm looking for:
我有一个 shell 脚本,如果文件被压缩(以 .gz 结尾),我需要在其中执行一个命令,如果不是,则需要执行另一个命令。我不太确定如何解决这个问题,以下是我正在寻找的内容的概述:
file=/path/name*
if [ CHECK FOR .gz ]
then echo "this file is zipped"
else echo "this file is not zipped"
fi
回答by rici
You can do this with a simple regex, using the =~
operator inside a [[...]]
test:
你可以用一个简单的正则表达式来做到这一点,=~
在[[...]]
测试中使用运算符:
if [[ $file =~ \.gz$ ]];
This won't give you the right answer if the extension is .tgz
, if you care about that. But it's easy to fix:
如果扩展名是.tgz
,这不会给你正确的答案,如果你关心的话。但它很容易修复:
if [[ $file =~ \.t?gz$ ]];
The absence of quotes around the regex is necessary and important. You could quote $file
but there is no point.
正则表达式周围没有引号是必要且重要的。你可以引用,$file
但没有意义。
It would probably be better to use the file
utility:
使用该file
实用程序可能会更好:
$ file --mime-type something.gz
something.gz: application/x-gzip
Something like:
就像是:
if file --mime-type "$file" | grep -q gzip$; then
echo "$file is gzipped"
else
echo "$file is not gzipped"
fi
回答by jthill
Really, the clearest and often easiest way to match patterns like this in a shell script is with case
实际上,在 shell 脚本中匹配这样的模式的最清晰且通常最简单的方法是使用 case
case "$f" in
*.gz | *.tgz )
# it's gzipped
;;
*)
# it's not
;;
esac
回答by Rahul Tripathi
You can try something like this:-
你可以尝试这样的事情:-
if [[ ${file: -3} == ".gz" ]]