Home > Net >  Need to output all binary and non-binary files and subdirectories (Bash)
Need to output all binary and non-binary files and subdirectories (Bash)

Time:09-16

still a beginner and in need of some assistance... I need to create a script that a user can use to run against their root directory to see what is binary and non-binary. If the files or subdirectories are non-binary, that needs to be shown in the output. The output of the script I have now shows that subdirectories with files in them are showing up as non-binary even though they are not empty. Any help is appreciated, thanks in advanced!

Code:

directoryPath="/../checker"
firstLevel='./*'
secondLevel='./*/*'
thirdLevel='./*/*/*'
fourthLevel='./*/*/*/*'

if [[ -d $directoryPath ]];                 
then
    for eachfile in $firstLevel $secondLevel $thirdLevel $fourthLevel
    do
        if [[ -s $eachfile ]];              
        then
            echo "$eachfile This is a binary file"
        else
            echo "$eachfile This is a non-binary file"
        fi
    done
else
    echo "$directoryPath is incorrect"
fi

Output:

./project/README.txt This is a binary file
./project/src This is a non-binary file
./project/testfile1.txt This is a binary file
**./project/src/main This is a non-binary file
./project/src/test This is a non-binary file
./project/src/main/example.jar This is a binary file
./project/src/test/example1.jar This is a binary file**

CodePudding user response:

The file command may give you more useful information about each file:

find . -exec file '{}'  

With a bash loop, use shopt -s globstar and for f in **; do ...

CodePudding user response:

  1. The -s is only testing if the file has contents -- not if it is binary.

  2. Use find if you want to descend only a fixed number of directory levels. Use can use recursive glob (with shopt -s globstar and for fn in */**; do) also.

  3. The file shell utility will give you better information on the type of file you are encountering. Example, ex.sh is a shell script, ascii_text is just a text file, and DSC_1714.JPG is an image file.

Examples:

% file ascii_text
ascii_text: ASCII text

% file ex.sh        
ex.sh: Bourne-Again shell script text executable, ASCII text

% file DSC_1714.JPG
DSC_1714.JPG: JPEG image data, Exif standard: [TIFF image data, little-endian, direntries=13, manufacturer=NIKON CORPORATION, model=NIKON Z 7, orientation=upper-left, xresolution=204, yresolution=212, resolutionunit=2, software=Ver.03.20, datetime=2022:08:03 18:30:24TIFF image data, little-endian, direntries=13, manufacturer=NIKON CORPORATION, model=NIKON Z 7, orientation=upper-left, xresolution=204, yresolution=212, resolutionunit=2, software=Ver.03.20, datetime=2022:08:03 18:30:24], baseline, precision 8, 8256x5504, components 3
  • Related