看看各种test运算符(这是针对测试命令本身的,但内置的 BASH 和 TCSH 测试或多或少是相同的)。
你会注意到-x FILE
says 文件存在并授予执行(或搜索)权限.
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
确定type文件的大小,尝试file命令。您可以解析输出以准确查看它是什么类型的文件。警告字: 有时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
The 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
, or SPARC
with 32-bit
).
Addendum
非常感谢,这似乎是可行的方法。在我将此标记为我的答案之前,您能否指导我必须对“文件”执行哪种类型的脚本 shell 检查(即哪种解析),以检查我是否可以执行程序?如果这样的测试在一般基础上很难进行,我至少想检查它是 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
基本上,我正在运行测试,如果成功,我会对输出进行 grepfile
命令。这grep -q
意味着不打印任何输出,但使用 grep 的退出代码来查看是否找到该字符串。如果您的系统不支持grep -q
, 你可以试试grep "regex" > /dev/null 2>&1
.
再次,输出file
命令可能因系统而异,因此您必须验证这些命令是否适用于您的系统。另外,我正在检查可执行位。如果一个文件是二进制可执行文件,但可执行位未打开,我会说它不可执行。这可能不是您想要的。