jchi2241
jchi2241

Reputation: 2226

bash set -eo pipefail not immediately exiting

#!/usr/bin/env bash
set -eo pipefail

sha256sum \
    Dockerfile-ci \
    frontend/pnpm-lock.yaml \
| sha256sum

If frontend/pnpm-lock.yaml does not exist, and the script above is run

sha256sum: frontend/pnpm-lock.yaml: No such file or directory
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

It correctly logs that the file doesn't exist, but it continues piping that into the next sha256sum. Shouldn't set -eo pipefail immediately exit the script on the first sha256sum command and not pipe into the second sha256sum?

Upvotes: 3

Views: 2966

Answers (2)

Ashish Sharma
Ashish Sharma

Reputation: 672

try to use below flag then it work. I have validated it.

#!/bin/bash
set -e -o pipefail

# to reset use
# set +e +o pipefail

Upvotes: -3

John Kugelman
John Kugelman

Reputation: 361739

pipefail doesn't cause the pipeline to abort early if a command fails. The pipeline still runs to completion, until all the commands have exited. That's true with or without pipefail.

What pipefail does do is ensure the return status is a failure if any of the commands fail. Without pipefail the pipeline fails only if the final command fails.

From the bash manual (emphasis added):

The exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail option is enabled (see The Set Builtin). If pipefail is enabled, the pipeline’s return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully. If the reserved word ! precedes the pipeline, the exit status is the logical negation of the exit status as described above. The shell waits for all commands in the pipeline to terminate before returning a value.

Upvotes: 7

Related Questions