Categories
Linux Mastering Development

How do a dynamically switch parts of a pipe?

I have a script which should execute a series of commands through a pipe. Depending of the arguments passed to the script:

  • Either it encrypts the file, computes its hash, and sends it to a REST service.
  • Or it compresses the file, computes its hash, and sends it to a REST service.
  • Or it simply reads the file, computes its hash, and sends it to a REST service.
if [ "$encryption" = "GPG" ]; then
    gpg2 \
        --batch \
        --passphrase-file "$keyFile" \
        --output - \
        --symmetric \
        --compress-level "$compressLevel" \
        "$filePath" | \
        ./scripts/sha1.py --store "$sha1Destination" | \
        curl --silent -X PUT --limit-rate "$limitRate" "$uri" -F files[]=@-
elif [ "$encryption" = "disabled" ]; then
    if [ "$compressLevel" > 0 ]; then
        gzip --stdout "$filePath" -"$compressLevel" | \
        ./scripts/sha1.py --store "$sha1Destination" | \
        curl --silent -X PUT --limit-rate "$limitRate" "$uri" -F files[]=@-
    else
        cat "$filePath" | \
        ./scripts/sha1.py --store "$sha1Destination" | \
        curl --silent -X PUT --limit-rate "$limitRate" "$uri" -F files[]=@-
    fi
fi

The second and third part of each chain of commands remains the same: only the first part changes, being gpg2 in one case, gzip in another, and cat in the last one.

I’m annoyed by the code duplication for the second and third part of the chain.

Is there a way to remove the code duplication, that is to do something like:

if [ "$encryption" = "GPG" ]; then
    ...
elif [ "$encryption" = "disabled" ]; then
    if [ "$compressLevel" > 0 ]; then
        ...
    else
        ...
    fi
fi

... | \
    ./scripts/sha1.py --store "$sha1Destination" | \
    curl --silent -X PUT --limit-rate "$limitRate" "$uri" -F files[]=@-

Leave a Reply

Your email address will not be published. Required fields are marked *