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

bash – 检查文件是否可执行

我想知道什么是最简单的方法来检查一个程序是否可执行与bash,而不执行它?它应该至少检查文件是否具有执行权限,并且是相同的架构(例如,不是Windows可执行文件或其他不支持的体系结构,如果系统是32位,则不是64位…)作为当前系统。
看看各种 test操作符(这是为了测试命令本身,但内置的BASH和TCSH测试或多或少相同)。

你会注意到,-x FILE表示FILE存在并且执行(或搜索)权限被授予。

BASH,Bourne,Ksh,Zsh Script

if [[ -x "$file" ]]
then
    echo "File '$file' is executable"
else
    echo "File '$file' is not executable or found"
fi

TCSH或CSH脚本:

if ( -x "$file" ) then
    echo "File '$file' is executable"
else
    echo "File '$file' is not executable or found"
endif

要确定文件的类型,请尝试使用file命令。您可以解析输出以查看它是什么类型的文件。 Word’o警告:有时文件将返回多行。这里是我的Mac上发生了什么:

$ file /bin/ls    
/bin/ls: Mach-O universal binary with 2 architectures
/bin/ls (for architecture x86_64):  Mach-O 64-bit executable x86_64
/bin/ls (for architecture i386):    Mach-O executable i386

file命令根据操作系统返回不同的输出。但是,可执行文件将在可执行程序中,通常架构也会出现。

比较上面的我在我的Linux盒子:

$ file /bin/ls
/bin/ls: ELF 64-bit LSB executable,AMD x86-64,version 1 (SYSV),for GNU/Linux 2.6.9,dynamically linked (uses shared libs),stripped

一个Solaris盒子:

$ file /bin/ls
/bin/ls:        ELF 32-bit MSB executable SPARC Version 1,dynamically linked,stripped

在所有三个中,您将看到可执行文件和体系结构(x86-64,i386或32位的SPARC)。

附录

Thank you very much,that seems the way to go. Before I mark this as my answer,can you please guide me as to what kind of script shell check I would have to perform (ie,what kind of parsing) on ‘file’ in order to check whether I can execute a program ? If such a test is too difficult to make on a general basis,I would at least like to check whether it’s a linux executable or osX (Mach-O)

在我的头顶,你可以做这样的东西在BASH:

if [ -x "$file" ] && file "$file" | grep -q "Mach-O"
then
    echo "This is an executable Mac file"
elif [ -x "$file" ] && file "$file" | grep -q "GNU/Linux"
then
    echo "This is an executable Linux File"
elif [ -x "$file" ] && file "$file" | grep q "shell script"
then
    echo "This is an executable Shell Script"
elif [ -x "$file" ]
then
    echo "This file is merely marked executable,but what type is a mystery"
else
    echo "This file isn't even marked as being executable"
fi

基本上,我运行测试,那么如果这是成功的,我对文件命令的输出执行grep。 grep -q意味着不打印任何输出,但使用grep的退出代码看看是否找到了字符串。如果你的系统不使用grep -q,你可以尝试grep“regex”> / dev / null 2>& 1。

同样,文件命令的输出可能因系统而异,因此您必须验证这些输出将在您的系统上工作。此外,我检查可执行位。如果一个文件一个二进制可执行文件,但可执行位未打开,我会说它不可执行。这可能不是你想要的。

原文地址:https://www.jb51.cc/bash/390289.html

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

相关推荐