bash – 检查文件是否可执行

前端之家收集整理的这篇文章主要介绍了bash – 检查文件是否可执行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道什么是最简单的方法来检查一个程序是否可执行与bash,而不执行它?它应该至少检查文件是否具有执行权限,并且是相同的架构(例如,不是Windows可执行文件或其他不支持的体系结构,如果系统是32位,则不是64位…)作为当前系统。
看看各种 test操作符(这是为了测试命令本身,但内置的BASH和TCSH测试或多或少相同)。

你会注意到,-x FILE表示FILE存在并且执行(或搜索)权限被授予。

BASH,Bourne,Ksh,Zsh Script

  1. if [[ -x "$file" ]]
  2. then
  3. echo "File '$file' is executable"
  4. else
  5. echo "File '$file' is not executable or found"
  6. fi

TCSH或CSH脚本:

  1. if ( -x "$file" ) then
  2. echo "File '$file' is executable"
  3. else
  4. echo "File '$file' is not executable or found"
  5. endif

要确定文件的类型,请尝试使用file命令。您可以解析输出以查看它是什么类型的文件。 Word’o警告:有时文件将返回多行。这里是我的Mac上发生了什么:

  1. $ file /bin/ls
  2. /bin/ls: Mach-O universal binary with 2 architectures
  3. /bin/ls (for architecture x86_64): Mach-O 64-bit executable x86_64
  4. /bin/ls (for architecture i386): Mach-O executable i386

file命令根据操作系统返回不同的输出。但是,可执行文件将在可执行程序中,通常架构也会出现。

比较上面的我在我的Linux盒子:

  1. $ file /bin/ls
  2. /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盒子:

  1. $ file /bin/ls
  2. /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:

  1. if [ -x "$file" ] && file "$file" | grep -q "Mach-O"
  2. then
  3. echo "This is an executable Mac file"
  4. elif [ -x "$file" ] && file "$file" | grep -q "GNU/Linux"
  5. then
  6. echo "This is an executable Linux File"
  7. elif [ -x "$file" ] && file "$file" | grep q "shell script"
  8. then
  9. echo "This is an executable Shell Script"
  10. elif [ -x "$file" ]
  11. then
  12. echo "This file is merely marked executable,but what type is a mystery"
  13. else
  14. echo "This file isn't even marked as being executable"
  15. fi

基本上,我运行测试,那么如果这是成功的,我对文件命令的输出执行grep。 grep -q意味着不打印任何输出,但使用grep的退出代码看看是否找到了字符串。如果你的系统不使用grep -q,你可以尝试grep“regex”> / dev / null 2>& 1。

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

猜你在找的Bash相关文章