Detect executables in bash [closed]

2

I am new in the bash language (GNU / linux) and a question has arisen in an exercise: I have to go through all the files in a directory, and for those that are executable, I save a variable 1, or a 0 in case of not being executable.

I tried to do if with those files whose extension is "* .exe", but later I read that in gnu / linux extensions are not used to avoid manipulations, but "magic numbers". Then I tried the file -z $nombreFichero command, but it does not work either.

How can I detect if the file is executable or not? This is the code I've been carrying so far:

#!/bin/bash

fichero=$(mktemp)

for nombre in $(find $1 -size +$2)  
do  
   if [ -x $nombre ];  
   then  
      ejecutable=1  
   else  
      ejecutable=0  
   fi

   echo "$nombre,${#nombre},'stat -c %u $nombre','stat -c %U $nombre','stat -c %h $nombre','stat -c %Y $nombre','stat -c %A $nombre',$ejecutable " >> $fichero
done

if [ -z "$2" ];   
then  
   for nombre in $(find $1 -size +0)  
   do  
      if [ -x $nombre ];  
      then  
         ejecutable=1  
      else  
         ejecutable=0  
      fi  
      echo "$nombre,${#nombre},'stat -c %u $nombre','stat -c %U $nombre','stat -c %h $nombre','stat -c %Y $nombre','stat -c %A $nombre',$ejecutable" >> $fichero  
   done  
fi  

cat "$fichero" | sort -k1r  

rm "$fichero"  
    
asked by Nacho 31.03.2017 в 21:35
source

1 answer

1

You can use the file command that determines the type of file that is passed as a parameter.

Running it in a text file:

$ file array_string.cpp   
  

array_string.cpp: C source, ASCII text

Running it in an executable file:

$ file array_string.exe   
  

array_string.exe: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU / Linux 2.6.24, BuildID [sha1] = c1b3d0b4539fd50758195bca5b55428795fc4280, not stripped

Running with the -i parameter, will show you the MIME information Multipurpose Internet Mail Extensions (or in Spanish multipurpose extensions Internet Mail )

$ file -i array_string.cpp 
  

array_string.cpp: text / x-c; charset = us-ascii

$ file -i array_string.exe 
  

array_string.exe: application / x-executable; charset = binary

And this last form of execution I think it's more convenient for the purpose you need it.

    
answered by 31.03.2017 / 23:33
source