-1

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
starball
  • 20,030
  • 7
  • 43
  • 238
Ran Mory
  • 1
  • 1

2 Answers2

2

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.

Roozbeh Sayadi
  • 318
  • 2
  • 13
  • I want to use file command but I don't know how to formulate the condition. Can you write the condition? – Ran Mory Dec 26 '21 at 05:56
  • `if [[ -z $(file temp.sh | grep "shell script") ]]; then echo "Not bash!"; else echo "bash"; fi` – Roozbeh Sayadi Dec 26 '21 at 05:59
  • But I don't know the file name. Also I want to know the full name of the file if it is a bash script file. How will this be? – Ran Mory Dec 26 '21 at 06:06
  • Here's a link on how to iterate through files in a folder and access their names while doing so: https://stackoverflow.com/questions/20796200/how-to-loop-over-files-in-directory-and-change-path-and-add-suffix-to-filename. – Roozbeh Sayadi Dec 26 '21 at 06:12
  • 2
    Avoid using the `[[ ... ]]` with subshell when it is unnecessary. This is enough (and simpler): `if file temp.sh | grep -q "shell script"; then ...; else ...; fi`. `grep` indicates in its return code (like most commands) whether it is successful or not. – syme Dec 26 '21 at 21:08
0

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
Humpity
  • 152
  • 1
  • 9