0

I have a list of folders. In every of those folders there may or may not be one or two files of a particular extension (specifically ".fastq" extension). What I want to do is write a script that enters these folders, checks if fastq file exists or not. The script I've written is below :

#!/bin/bash
echo Beginning operation
echo
for folder in $(ls -d */);
do
    cd ${folder%%/};
    myfolder=${folder::-1}
    echo
    echo Entered $myfolder

    fastq_test=(´find ./ -maxdepth 1 -name "*.fastq"´)
    if [ ${#fastq_test[@]} -gt 0 ];
    then
        echo There are FASTQ files, will not do the operation
    else
        echo There are no FASTQ files, proceeding with operation
        #operation here
    fi
    cd ..
    echo Exited $myfolder
    echo 
done
echo Ended Operation

My problem is that this script doesn't work - it finds FASTQ files in folders that do not have them. Is there any better way?

ivan199415
  • 375
  • 3
  • 12
  • 1
    Check your scripts with shellcheck.net . See https://stackoverflow.com/questions/2937407/test-whether-a-glob-has-any-matches-in-bash – KamilCuk Nov 17 '21 at 15:31
  • Those non-standard quotes `´` are not syntactically valid, it looks like you are trying to use backticks (which you also should not use here, [for several reasons](https://www.iki.fi/era/unix/award.html#backtick)) but you are simply examining whether the literal string `´find ./ -maxdepth 1 -name "*.fastq"´` is nonempty, which is of course it is (though that is a painful way to test it; simply `if [ "string" ]` does the same thing). – tripleee Nov 17 '21 at 15:44
  • ivan199415, @KamilCuk, I updated my answer. The question was a bit more complex than just `Test whether a glob has any matches in Bash` – Fravadona Nov 17 '21 at 16:43

1 Answers1

2

In bash you can do:

#!/bin/bash

for dir in ./*/
do
    if compgen -G "$dir*.fastq" > /dev/null
    then
        echo 'There are FASTQ files, will not do the operation'
    elif pushd "$dir" > /dev/null
    then
        echo 'There are no FASTQ files, proceeding with operation'
        # operations...
        popd > /dev/null
    fi
done

notes:
  • The trailing slash in ./*/ makes it so that the glob only matches directories, and the ./ at the start is a safety against names that start with dash.
  • compgen -G 'glob' is a great bash way for testing the existence of files/directories that match a glob. That said, its output isn't worth anything in your case (and in general when used for glob matching, because you'll need the /./ | ././ trick for detecting newlines in a file/dir name).
  • pushd will cd you to "$dir"; then you use popd to return to the previous directory. pushd popd are useful but their output is annoying.
Fravadona
  • 13,917
  • 1
  • 23
  • 35
  • Wonderful solution, and thanks for all the notes. Everything works, all I need to do now is input the operation. Thanks. – ivan199415 Nov 18 '21 at 09:37