微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用Bash中的file命令检查文件是否可执行?

如何解决如何使用Bash中的file命令检查文件是否可执行?

我有一项作业,要求我使用file命令检查文件是否为可执行文件类型。

作业中使用的措词如下:

应该使用file命令一般确定参数是哪种文件,尤其是文件是否为可执行文件类型时。如果文件是可执行文件,则file命令的输出将包含特殊的“ executable”关键字。

问题的进一步内容是:

  1. 使用文件并在输出中寻找“ executable”关键字,以确定文件是否为可执行文件类型。

到目前为止,我一直找不到任何说明该操作方法的文档。当我在CentOS8中的bash脚本上对此进行测试时,它将作为输出返回:

validate.sh: ASCII text

Edit1 / found_the_answer_edit:我尝试使用ti7的使用测试脚本的想法,它得到的输出与他们获得的输出相同。这让我开始思考。我的作业脚本需要对它们进行一些格式化。具体来说,为了获得我们脚本的信誉,我们必须具备:

#START SCRIPT
#username
``
at the beginning of the file and:

#END脚本

at the end of it. I deleted these bits in my validate.sh file and when I tested it again with the file command I got the same output that I got from the test script. So the answer is that there isn't anything special. File just can't deal with a file that doesn't start with "#!/bin/bash"

解决方法

您的脚本validate.sh可能不是 可执行文件,因为file确定了它!这可能是因为标题错误了

% cat test.sh
#!/bin/bash
echo "foo"
% file test.sh
test.sh: Bourne-Again shell script text executable,ASCII text

解决后,您可以检查响应中的executable关键字,也许使用grep

% file test.sh | grep -q executable ; echo $?
0
% touch test-empty.sh
% file test-empty.sh | grep -q executable ; echo $?
1

如果您不被迫使用file,则使用测试的-x arg可能会比建议的here好得多,因为file不会检查权限,而不是文件格式是可执行文件

请注意,测试命令命令实际上是[[[,两者之间存在细微差别

[[ -x "validate.sh" ]] && echo "executable" || echo "not executable"

您可以使用ls来检查其权限,该权限列出目录中的文件以及它们的属性(可选)

ls -lhaF

您可以使用chmod(通常为chmod +x)将脚本设为可执行文件

,

不确定这是否实际上是在Windows上运行的bash,也许是WSL。如果是,则文件实际上将返回给定的Windows exe文件是可执行文件。

file write.exe

write.exe: PE32+ executable (GUI) x86-64,for MS Windows

考虑到这一点,您可以通过管道传输到grep并测试输出,即

file write.exe | grep -q executable && echo "Executable" || echo "Not executable"

Executable

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。