<分区>
我有一个 shell 脚本,如果一个文件被压缩(以 .gz 结尾),我需要执行一个命令,如果没有,我需要执行另一个命令。我不太确定如何处理这个问题,以下是我正在寻找的内容的概述:
file=/path/name*
if [ CHECK FOR .gz ]
then echo "this file is zipped"
else echo "this file is not zipped"
fi
<分区>
我有一个 shell 脚本,如果一个文件被压缩(以 .gz 结尾),我需要执行一个命令,如果没有,我需要执行另一个命令。我不太确定如何处理这个问题,以下是我正在寻找的内容的概述:
file=/path/name*
if [ CHECK FOR .gz ]
then echo "this file is zipped"
else echo "this file is not zipped"
fi
最佳答案
你可以用一个简单的正则表达式来做到这一点,在 [[...]]
测试中使用 =~
运算符:
if [[ $file =~ \.gz$ ]];
如果扩展名是 .tgz
,如果您关心它,这不会给您正确的答案。但它很容易修复:
if [[ $file =~ \.t?gz$ ]];
正则表达式周围没有引号是必要且重要的。你可以引用 $file
但没有意义。
使用 file
实用程序可能会更好:
$ file --mime-type something.gz
something.gz: application/x-gzip
类似于:
if file --mime-type "$file" | grep -q gzip$; then
echo "$file is gzipped"
else
echo "$file is not gzipped"
fi
关于bash - 在 bash 中检查文件扩展名的最简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18278990/