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)。 附录
在我的头顶,你可以做这样的东西在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。 同样,文件命令的输出可能因系统而异,因此您必须验证这些输出将在您的系统上工作。此外,我检查可执行位。如果一个文件是一个二进制可执行文件,但可执行位未打开,我会说它不可执行。这可能不是你想要的。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |