[英]How do I check if a file is executable using the file command in Bash?
我有一项作业,其中要求我使用 file 命令来检查文件是否为可执行类型。
作业中使用的措辞如下:
file 命令应该用于一般地确定参数是什么类型的文件,特别是文件是否是可执行类型。 如果文件是可执行类型,文件命令的输出将包含特殊的“可执行”关键字。
进一步在问题中,它指出:
- 使用 file 并在输出中查找“executable”关键字以确定文件是否为可执行类型。
到目前为止,我一直无法找到任何解释如何执行此操作的文档。 当我在 CentOS8 中的 bash 脚本上对此进行测试时,它会将其作为输出返回:
validate.sh: ASCII text
Edit1/found_the_answer_edit:我尝试使用 ti7 的使用测试脚本的想法,它得到的输出与他们得到的输出相同。 这让我思考。 我的作业脚本需要对它们进行一些格式化。 具体来说,为了获得我们脚本的荣誉,我们必须:
#START SCRIPT
#username
``
at the beginning of the file and:
#结束脚本
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
,则按照此处的建议使用 test 的-x
arg 可能会好得多,因为file
不检查权限,而是文件格式是可执行的
注意 test 命令命令实际上是[
或[[
有细微的差别
[[ -x "validate.sh" ]] && echo "executable" || echo "not executable"
您可以使用ls
来检查它的权限,它会列出目录中的文件以及它们的可选属性
ls -lhaF
您可以使用chmod
使您的脚本可执行(简单地说, chmod +x
)
不确定这是否真的是在 Windows 上运行的 bash,所以可能是 WSL。 如果是,文件实际上将返回给定的 Windows exe 文件是可执行的。
IE
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.