在bash中判断文件是否为PDF

Sha*_*ble 1 pdf bash file-type

我需要编写一个bash脚本来判断文件是否是pdf文件.但是,我不能简单地使用文件名或扩展名.

例如:

test.pdf.encrypt - 由于文件本身已加密且文件是计算机无法识别的未知类型,因此无法打开.

test.pdf.decrypt - 即使扩展名是.decrypt也会打开

由于查看扩展名没有帮助,加密和解密文件都在名称中间有.pdf,有没有办法让系统测试并查看文件是否可以用PDF阅读器阅读?

我只需要在bash中输入if语句的命令.

if [this file is a working pdf file]; do
   echo "$file is a working pdf file."
fi
Run Code Online (Sandbox Code Playgroud)

els*_*ooo 8

每个 PDF 文件都以%PDF. 您可以比较指定文件的前 4 个字符,以确保它是 PDF。

FILE="/Users/Tim/Documents/My File.pdf"
if [ $(head -c 4 "$FILE") = "%PDF" ]; then
    echo "It's a PDF!"
fi
Run Code Online (Sandbox Code Playgroud)


Ans*_*ers 6

另一种选择是file在文件上使用:

type="$(file -b $file)"
if [ "${type%%,*}" == "PDF document" ]; then
  echo "$file is a PDF file."
fi
Run Code Online (Sandbox Code Playgroud)