Checking files in bash scripts

In job scripts you sometimes want to check whether a file exists and only run an action if it doesn’t exist. For example you might want to run a quality cleaning step on multiple files on an HPC. Here, you might want to skip the cleaning step if the output file already exists to avoid re-running computationally costly tasks. Or you might want to generate a clear error message if an input file is missing for easier troubleshooting.

For this tutorial, first create two files: a sample list and empty file which we will use in later sections:

# Generate a list of samples that we want to analyse
echo -e "s1\ns2\ns3\ns4" > samples

# Generate an empty file to test some commands below
touch empty_file

Action when a file does not exist

Let’s begin with a basic example and add a file verification in case a file that doesn’t exist yet.

For this tutorial, we assume that you want to do some quality cleaning but to keep your jobs efficient, you only want to run the cleaning step if the file does not exist. For this example, we assume that the cleaning step produces a file called cleaned.fastq.

The -f operator returns TRUE if the file exists. We can use this in an if/else operation and perform a specific action only when the operator returns TRUE and do something else if it does not.

Notes:

  • When writing this yourself a common error is to not add spaces here [ -f and here ]. This is an important part of the syntax, which when not added will create an error.
  • In the code below the touch command is used to simulate the cleaning script generating an output file. In a real scenario you would remove this line and add your actual command there instead.
OUTPUT="cleaned.fastq"

# Check if file exists
if [ -f "$OUTPUT" ]; then 
    echo -e "\n${OUTPUT} exists. Nothing to be done"
else 
    echo -e "\nRun cleaning script. Generating output:" 
    touch "$OUTPUT"
fi

# confirm the file was created
ls "$OUTPUT"

This returns:

Run cleaning script. Generating output:
cleaned.fastq

So we see that the cleaning script would be executed. If we would re-run the command, then the script recognizes that the cleaned.fastq file already exists and won’t rerun the cleaning step:

OUTPUT="cleaned.fastq"

if [ -f "$OUTPUT" ]; then 
    echo -e "\n${OUTPUT} exists. Nothing to be done"
else 
    echo -e "\nRun cleaning script. Generating output:" 
    touch "$OUTPUT"
fi
cleaned.fastq exists. Nothing to be done

You can also negate things and check if a file does not exist using !:

# Remove the file created in the previous example to start fresh
rm cleaned.fastq

OUTPUT="cleaned.fastq"

# Check if the file does not exist and then do something 
if [ ! -f "$OUTPUT" ]; then 
    echo -e "\n${OUTPUT} does not exist. Run cleaning script. Generating output:" 
    touch "$OUTPUT"
fi

# confirm the file was created
ls "$OUTPUT"
cleaned.fastq does not exist. Run cleaning script. Generating output:
cleaned.fastq

Action when a file exists but is empty

Sometimes tools might run incorrectly and generate an output but this output is empty. In this case you would want to rerun your cleaning step on that specific file.

The -s operator returns true if the file exists and has a size greater than zero (i.e., is non-empty).

OUTPUT="empty_file"

if [ -s "$OUTPUT" ]; then 
    echo -e "\n${OUTPUT} exists and is non-empty. Nothing to be done"
else 
    echo -e "\n${OUTPUT} is empty, run cleaning script. Generating output:" 
    touch "$OUTPUT"
fi

# confirm the file was created
ls "$OUTPUT"
empty_file is empty, run cleaning script. Generating output:
empty_file

Note: in a real script, the else branch would rerun the tool that generates the file. Here we use touch as a placeholder, which creates again an empty file and the check would trigger again on the next run.

Watch out with compressed files. -s only checks that a file is bigger than 0 bytes. Even a .gz file without any reads is about 20 bytes, so -s is true for it, see Why not just -s?.

Combining checks

We can also check if two files exist, which might be useful if your tool requires two inputs. To do this, you can combine checks with the AND statement using &&.

Note: When combining conditions, use[[ instead of [. This construct is a bash built-in that handles compound conditions more reliably. You can use [[ even if you are not combining two checks. That is because the [[ has some other features such as handling empty variables without returning a syntax error.

if [[ -f samples && -f cleaned.fastq ]]; then 
    echo -e "\nBoth files exist. Nothing to be done"
else    
    echo "File missing. Re-run file generation step"
fi
Both files exist. Nothing to be done

You can be more defensive and use an elif statement to know exactly which file does not exist. Here, negation is again useful.

if [[ ! -f samples ]]; then 
    echo -e "\nsamples does not exist."
elif [[ ! -f cleaned.fastq ]]; then
   echo -e "\ncleaned.fastq does not exist."
else    
    echo "All files exist. Nothing to be done."
fi
All files exist. Nothing to be done.

Note: elif checks conditions sequentially and stops at the first match. If both files are missing, only the first missing file will be reported. If you wanted to report each file, you can instead use two separate if statements.

Putting everything together

Looping across all samples

Assume now that we want to run our cleaning step on all samples. A loop would be a natural way to do this. If you want to learn more about loops go here. In our case we could do the following:

# Generate a dummy output file that exists 
echo "some content" > s1.cleaned.fastq

for ID in $(cat samples); do
    OUTPUT="${ID}.cleaned.fastq"

    echo "Processing $ID"
    echo "---------------"

    if [[ -s "$OUTPUT" ]]; then
        echo -e " ${OUTPUT} exists and is non-empty, skipping\n"
    else
        echo -e "Running cleaning step and generating ${OUTPUT} \n"
    fi
done

We see that s1 is handled differently since it already exists:

Processing s1
---------------
s1.cleaned.fastq exists and is non-empty, skipping

Processing s2
---------------
Running cleaning step and generating s2.cleaned.fastq

Processing s3
---------------
Running cleaning step and generating s3.cleaned.fastq

Processing s4
---------------
Running cleaning step and generating s4.cleaned.fastq

This -s check on the output file is fine to learn the idea. In a real job script, it can skip a sample whose output is broken. Use a marker file instead, see Skip finished samples safely.

This page uses for ID in $(cat samples), because the sample list has one ID per line. The for-loops tutorial also teaches you how to use a while loop, which you need when your list has more than one column, for example a sample ID and a file path. Regardless of how you write the loop: if your sample list comes from Excel or Windows, check it for Windows line endings first, see Handling DOS file format issues.

break: Stopping a loop if something is wrong

Sometimes you want to stop the entire loop if something is wrong, rather than skipping a sample. This is useful when a missing or empty file indicates a problem in a previous step that needs to be resolved before continuing.

For this example let’s look at this case: You performed the quality cleaning step and want to proceed with the next step and assembly the reads into contigs, i.e. into longer stretches of DNA. Maybe something went wrong during the quality cleaning and some of your cleaned reads are empty. Here, you actually might want to stop the pipeline since the assembly part is computationally expensive and first get a useful error message that allows you to troubleshoot before trying again.

The assembly process typically needs two inputs called the forward and reverse reads. While the details of what these files are is not important, this is a good usage case of using the OR keyword || to test whether forward or reverse file is missing. We also will now make use a new keyword called break that result in the loop stopping if an issue occurs.

# Only generate dummy files for s1 to simulate a partially completed pipeline
# Forward and reverse reads are typically input files for many computation tasks
echo "some content" > s1_forward_cleaned.fastq
echo "some content" > s1_reverse_cleaned.fastq

# Run the loop
for ID in $(cat samples); do
    CLEANED_READS_F="${ID}_forward_cleaned.fastq"
    CLEANED_READS_R="${ID}_reverse_cleaned.fastq"

    echo "Processing $ID"
    echo "---------------"

    if [[ ! -s "$CLEANED_READS_F" || ! -s "$CLEANED_READS_R" ]]; then
        echo "ERROR: ${CLEANED_READS_F} or ${CLEANED_READS_R} is missing or empty. Stopping pipeline."
        break
    fi

    echo -e "Both input files exist and are non-empty. Running assembly for $ID\n"
done

echo -e "\nScript finished"

We see:

Processing s1
---------------
Both input files exist and are non-empty. Running assembly for s1

Processing s2
---------------
ERROR: s2_forward_cleaned.fastq or s2_reverse_cleaned.fastq is missing or empty. Stopping pipeline.

Script finished

So the loop now stops when the one of the S2 files is missing.

exit 1: Stopping a script if something is wrong

Important for longer scripts: break stops the loop but does not stop the script. Any commands written after the done keyword will still be executed, even if break was triggered. To stop the entire script, use exit 1 instead of break. The 1 signals to the system that the script ended due to an error (exit code 0 means success).

exit ends the whole shell that runs it. If you paste the loop below into your terminal, exit closes your terminal. So save it in a file instead, for example with nano stop_test.sh:

for ID in $(cat samples); do
    CLEANED_READS_F="${ID}_forward_cleaned.fastq"
    CLEANED_READS_R="${ID}_reverse_cleaned.fastq"

    echo "Processing $ID"
    echo "---------------"

    if [[ ! -s "$CLEANED_READS_F" || ! -s "$CLEANED_READS_R" ]]; then
        echo "ERROR: ${CLEANED_READS_F} or ${CLEANED_READS_R} is missing or empty. Stopping pipeline."
        exit 1
    fi

    echo -e "Both input files exist and are non-empty. Running assembly for $ID\n"
done

echo -e "\nScript finished" # This line is never reached because exit 1 stops the script

Then run the script with bash. $? holds the exit code of the last command, here the script. echo "exit code: $?" prints it, with “exit code:” as a label in front:

bash stop_test.sh
echo "exit code: $?"

For me this prints:

Processing s1
---------------
Both input files exist and are non-empty. Running assembly for s1

Processing s2
---------------
ERROR: s2_forward_cleaned.fastq or s2_reverse_cleaned.fastq is missing or empty. Stopping pipeline.
exit code: 1

“Script finished” is never printed, and the exit code is 1.

In a SLURM job script, the job stops at exit 1 and SLURM marks it as failed. You can check this with sacct: the State column shows FAILED instead of COMPLETED. For how to use sacct, see this section. The message from echo ends up in the SLURM output file, because echo writes to the normal output. By default, SLURM writes normal output and error messages to the same file. If your job script sets a separate error file with #SBATCH --error, you can send the message there instead: add >&2 at the end of the echo line.

Which exit code to use

Line in the script Meaning What SLURM sees
exit 0 Stop here, all is fine. For example: in a job script for one sample, the output of that sample already exists success
exit 1 Stop here, something went wrong failure
no exit The script ends after its last line, with the exit code of that line depends on the last line

Any number other than 0 means failure. For example, 127 means that bash could not find the command or the script you asked it to run.

The last row is the tricky one. Save these two scripts as exit_1.sh and no_exit.sh, for example with nano. ls stands in for a real tool: like a tool, it fails when its input file is missing. || between two commands means: run the second command only if the first one fails.

# exit_1.sh
ls s2_forward_cleaned.fastq || exit 1
echo "Done"
# no_exit.sh
ls s2_forward_cleaned.fastq
echo "Done"

Run both with bash and print the exit codes. echo -e with \n at the end adds an empty line, so the output of the two scripts is easier to tell apart:

bash exit_1.sh
echo -e "exit code: $?\n"
bash no_exit.sh
echo -e "exit code: $?\n"

This prints:

ls: cannot access 's2_forward_cleaned.fastq': No such file or directory
exit code: 1

ls: cannot access 's2_forward_cleaned.fastq': No such file or directory
Done
exit code: 0

Both scripts show the same error. But no_exit.sh goes on, prints “Done”, and ends with exit code 0, because its last line worked. In a job, SLURM would report this job as successful, and you would only find the error by reading the log files.

exit always stops the whole script, also exit 0. So inside a loop over samples, don’t use exit 0 to skip a sample that is already done: the samples after it never run, and you get no error. To skip one sample and go on with the next, use continue or if/else (see below). In a SLURM job array, this is different: each task runs the script for one sample only, so there exit 0 ends just that one task, which is what you want.

continue keyword

The above works but we might want a different behavior and run the assembly on all files if the input files exist and for all other cases output a clear error message. The continue keyword does just that. Let’s begin and see what happens if the we don’t use the break keyword:

# Create dummy files for every sample except S2 to illustrate the process
echo "some content" > s3_forward_cleaned.fastq
echo "some content" > s3_reverse_cleaned.fastq
echo "some content" > s4_forward_cleaned.fastq
echo "some content" > s4_reverse_cleaned.fastq

# Run the loop
for ID in $(cat samples); do
    CLEANED_READS_F="${ID}_forward_cleaned.fastq"
    CLEANED_READS_R="${ID}_reverse_cleaned.fastq"

    echo "Processing $ID"
    echo "---------------"

    if [[ ! -s "$CLEANED_READS_F" || ! -s "$CLEANED_READS_R" ]]; then
        echo "ERROR: ${CLEANED_READS_F} or ${CLEANED_READS_R} is missing or empty. Skipping sample."
    fi

    echo -e "Both input files exist and are non-empty. Running assembly for $ID\n"
done

This prints:

Processing s1
---------------
Both input files exist and are non-empty. Running assembly for s1

Processing s2
---------------
ERROR: s2_forward_cleaned.fastq or s2_reverse_cleaned.fastq is missing or empty. Skipping sample.
Both input files exist and are non-empty. Running assembly for s2

Processing s3
---------------
Both input files exist and are non-empty. Running assembly for s3

Processing s4
---------------
Both input files exist and are non-empty. Running assembly for s4

We proceed to work through all 4 files but looking closely at what happens with S2, we see that the script:

  1. Acknowledges that files are missing
  2. Tries to run the Action anyhow, which in a real example would produce an error

By using continue we can skip the full loop for a sample where something is missing:

# Run the loop
for ID in $(cat samples); do
    CLEANED_READS_F="${ID}_forward_cleaned.fastq"
    CLEANED_READS_R="${ID}_reverse_cleaned.fastq"

    echo "Processing $ID"
    echo "---------------"

    if [[ ! -s "$CLEANED_READS_F" || ! -s "$CLEANED_READS_R" ]]; then
        echo "ERROR: ${CLEANED_READS_F} or ${CLEANED_READS_R} is missing or empty. Skipping sample."
        continue
    fi

    echo -e "Both input files exist and are non-empty. Running assembly for $ID\n"
done

Returns:

Processing s1
---------------
Both input files exist and are non-empty. Running assembly for s1

Processing s2
---------------
ERROR: s2_forward_cleaned.fastq or s2_reverse_cleaned.fastq is missing or empty. Skipping sample.
Processing s3
---------------
Both input files exist and are non-empty. Running assembly for s3

Processing s4
---------------
Both input files exist and are non-empty. Running assembly for s4

Now we see that nothing is done for S2, exactly what we want.

Important: if you use this inside a SLURM script, the error message ends up in the SLURM output file (see the exit 1 section above). Make sure to always read the SLURM log files to catch any issues with your script.

Alternative approach: The same behavior can be written using if/else, which makes both the error and the action branch explicitly visible. This can be easier to read when the loop body is long or when sharing code with others who are less familiar with continue.

for ID in $(cat samples); do
    CLEANED_READS_F="${ID}_forward_cleaned.fastq"
    CLEANED_READS_R="${ID}_reverse_cleaned.fastq"

    echo "Processing $ID"
    echo "---------------"

    if [[ ! -s "$CLEANED_READS_F" || ! -s "$CLEANED_READS_R" ]]; then
        echo "ERROR: files missing or empty for ${ID}"
    else
        echo -e "Running assembly for $ID\n"
    fi
done

Skipping samples that already finished

The checks on this page look at input files. If you want a job script that you can submit again, and that skips the samples that already finished, the check has to decide whether a sample is done. That is harder than it looks. For example, -s is true for a .gz file without reads, and for a file that was cut off halfway.

Skip finished samples safely gives you a template to copy into your job scripts. It also shows how to test a check with broken files, and how to check the outputs after a job.

Summary

Now you learned how to design code to more explicitly handle missing input files:

  • Use -f to check whether a file exists and -s to check whether a file exists and is non-empty. Prefer [[ over [ when writing conditions in bash scripts
  • Use break to stop a loop entirely when a missing or empty file indicates a problem that needs to be resolved before continuing
  • Use continue to skip the current sample and proceed to the next iteration when a file is missing. Note that continue is only meaningful when there is code after the if block that should be skipped. Without that, the loop advances to the next iteration anyway, making continue redundant
  • Use if/else as a readable alternative to continue, particularly for longer loop bodies or when sharing code with others
  • Use exit 1 to stop a script when something is wrong. exit 0 also stops the whole script, so inside a loop use continue to skip a sample that is done. Without exit, the last line decides, so a final echo "Done" can hide a failure
  • To skip samples that already finished, don’t write a new check for every script. Use the template on Skip finished samples safely

A note on GenAI-generated code: GenAI tools often add continue or || continue to skip a sample when a file is missing. Check that the script prints a clear message before it skips, as in the examples above, and read the log files after the job. For more patterns to look for, see Checking GenAI-generated scripts.