Search code examples
bashshellgunzip

Output of command as variable


I'm writing a PBS script to process many files at once and perform multiple actions.

I would like to start by unzipping .gz files (which I later zip) and then process the unzipped file.

The following will unzip the file in $file, but I once I have unzipped the file, I would like the variable $file to refer to the unzipped version:

for file in $READS/*2.fq.gz;
do
    gunzip $file
    # continue script with the gunzipped file  
done

Something like:

for file in $READS/*2.fq.gz;
do
    file=gunzip $file
    # continue script with the gunzipped file  
done

Solution

  • You want to remove the .gz suffix on $file:

    file=${file%.gz}
    

    Note that you probably also want to check the result of the gunzip command to see if it failed:

    for file in $READS/*2.fq.gz;
    do
        if gunzip $file; then
            file=${file%.gz}
            # continue script with the gunzipped file
        else
            # gunzip failed (corrupt file?) and already output an error message
            # try to recover?
        fi
    done