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