• 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[@]}"
do
    # Here I will write the condition that the file is found in the folder $k
done

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:

#!/bin/bash
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.
e.g

#!/bin/bash
arr=(~/*)
for i in "${arr[@]}"
do
    type=`file -b $i | awk '{print $2}'`
    if  [[ $type = shell ]];then
        echo $i is a shell script
    fi
done

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.