简体   繁体   中英

How do I search for bash script files without having a specific extension within a folder?

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

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.

The file command determines a file type. eg

#!/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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM