Dav*_* W. 93
看看各种测试操作符(这是测试命令本身,但内置的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
Run Code Online (Sandbox Code Playgroud)
TCSH或CSH脚本:
if ( -x "$file" ) then
echo "File '$file' is executable"
else
echo "File '$file' is not executable or found"
endif
Run Code Online (Sandbox Code Playgroud)
要确定文件类型,请尝试使用file命令.您可以解析输出以确切地查看它是什么类型的文件.单词'o警告:有时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
Run Code Online (Sandbox Code Playgroud)
该file命令根据OS返回不同的输出.但是,这个词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
Run Code Online (Sandbox Code Playgroud)
还有一个Solaris盒子:
$ file /bin/ls
/bin/ls: ELF 32-bit MSB executable SPARC Version 1, dynamically linked, stripped
Run Code Online (Sandbox Code Playgroud)
在所有三个,你会看到这个词executable和架构(x86-64,i386,或SPARC用32-bit).
非常感谢,这似乎是要走的路.在我将此标记为我的答案之前,您是否可以指导我在"文件"上执行哪种脚本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
Run Code Online (Sandbox Code Playgroud)
基本上,我正在运行测试,如果成功,我会对file命令的输出执行grep .这grep -q意味着不打印任何输出,但使用grep的退出代码来查看我是否找到了该字符串.如果您的系统没有grep -q,您可以尝试grep "regex" > /dev/null 2>&1.
同样,file命令的输出可能因系统而异,因此您必须验证这些命令是否适用于您的系统.另外,我正在检查可执行位.如果文件是二进制可执行文件,但可执行文件位未打开,我会说它不可执行.这可能不是你想要的.
此处给出的解决方案在目录或符号链接(或两者)上都失败。在 Linux 上,您可以使用以下命令测试文件、目录和符号链接:
if [[ -f "$file" && -x $(realpath "$file") ]]; then .... fi
Run Code Online (Sandbox Code Playgroud)
在 OS X 上,您应该能够使用自制软件安装 coreutils 并使用grealpath.
isexec函数为方便起见,您可以定义一个函数:
isexec() {
if [[ -f "$1" && -x $(realpath "$1") ]]; then
true;
else
false;
fi;
}
Run Code Online (Sandbox Code Playgroud)
或者干脆
isexec() { [[ -f "$1" && -x $(realpath "$1") ]]; }
Run Code Online (Sandbox Code Playgroud)
然后您可以使用以下方法进行测试:
if `isexec "$file"`; then ... fi
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
99604 次 |
| 最近记录: |