看看各种test 运算符(这是针对测试命令本身的,但内置的 BASH 和 TCSH 测试或多或少相同)。
您会注意到-x FILE 表示文件存在并且已授予执行(或搜索)权限。
BASH、Bourne、Ksh、Zsh 脚本
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 Warning:有时file 会返回不止一行。以下是我的 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 命令根据操作系统返回不同的输出。但是executable这个词会出现在可执行程序中,通常架构也会出现。
将上面的内容与我在 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
在所有三个中,您都会看到单词 executable 和架构(x86-64、i386 或 SPARC 和 32-bit)。
附录
非常感谢,这似乎是要走的路。在我将此标记为我的答案之前,请您指导我必须对“文件”执行什么样的脚本外壳检查(即,什么样的解析)以检查我是否可以执行程序?如果这样的测试很难在一般基础上进行,我至少想检查它是 linux 可执行文件还是 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
基本上,我正在运行测试,如果测试成功,我会对file 命令的输出执行 grep。 grep -q 表示不打印任何输出,而是使用 grep 的退出代码查看是否找到该字符串。如果你的系统不接受grep -q,你可以试试grep "regex" > /dev/null 2>&1。
同样,file 命令的输出可能因系统而异,因此您必须验证这些是否可以在您的系统上运行。另外,我正在检查可执行位。如果文件是二进制可执行文件,但可执行位未打开,我会说它不可执行。这可能不是你想要的。