Home > Software engineering >  How to loop through files with executable permissions?
How to loop through files with executable permissions?

Time:07-17

I'm trying to loop through several folders with different files. However, some files can be recognized and some cannot. I looked more into it and realized that it's only the green files that I cannot get the correct path. After reading more about it, it looks like green files are executable with this type of permission "-rwxrwxr--". I can loop through red files with this permission "-rw-rw-r--".

Here's a quick example of the loop.

for i in "${arr[@]}"
do
echo    /storage/data/${i}_*_R1.fastq.gz
done

For files with with this permission "-rw-rw-r--", the loop returns paths like this /storage/data/Sample1_ABCD_R1.fastq.gz. However, for files with permission "-rwxrwxr--" the output is this /storage/data/Sample2_*_R1.fastq.gz and I cannot process them. I tried removing the executable permission using chmod -x filename but it says Operation not permitted. I think this is because the files were originally created by someone else and shared with me. Is there an easier way to loop through these files without having to do it manually? Thanks!

CodePudding user response:

You could try the -x test flag to see if the file is executable by the current user.

for i in "${arr[@]}"; do
    test -x "$i" && echo "$i is executable"
done

CodePudding user response:

A different approach is by using find. You could do this in commandline:

find -executable -exec do_stuff_with_what_find_found {} \;

If you just wanted to find files that had execute permission, just use find -executable and find will return results based on your current working directory.

-exec flag executes given shell command upon the files that pass your given test, in this case is whichever file has execute permission.

  • Related