• Uncategorized

About arrays : How-do-I-search-for-bash-script-files-without-having-a-specific-extension-within-a-folder

Question Detail

I want to find bash script files under folders in Array.
But bash script files do not have a specified extension.
I wrote something like this:

for i in "${array[@]}"
    # Here I will write the condition that the file is found in the folder $k

Question Answer

If your scripts have #!/bin/bash or #!/bin/sh in their first line (as they should), then you can use the file command to check if a file is a script or not.

For example, take this script:

echo "I am a script!"

Output of file filename.sh will be filename.sh: Bourne-Again shell script, ASCII text executable, which is indicating it is a shell script. Note that the file command does not use the extension of the file to indicate its format, but uses the content of it.

If you don’t have those lines at the beginning of your file, You can try to run every file (command: bash filename.ext) and the check if it was run successfully or not by checking the value of the variable ${?}. This is not a clean method but it sure can help if you have no other choices.

The file command determines a file type.

for i in "${arr[@]}"
    type=`file -b $i | awk '{print $2}'`
    if  [[ $type = shell ]];then
        echo $i is a shell script

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.