3

I am currently doing this in a POSIX shell script:

success=false

pv --wait "$input_filename" | openssl enc -aes-256-cbc -d -salt -out "$output_filename" && success=true

if [ "$success" = "true" ]
...

The problem is, I am not quite sure, if I do this correctly.

For instance, I don't get the difference between that approach and just checking $?.

Why I care?

Well, because ShellCheck.net warned me:

SC2181 Check exit code directly with e.g. 'if mycmd;', not indirectly with $?.

1
  • Take that comment about using if cmd over checking $? as a recommendation, not a rule. Using $? explicitly is just not necessary, if you can put the cmd on the if condition directly. But it's also about preference, there's nothing wrong with testing $?. Though I'd rather write the test against $? than use an extra temporary, unless there's some other reason to have the variable.
    – ilkkachu
    Dec 10, 2017 at 10:03

2 Answers 2

6

If you only need to check whether the command succeded or not, the if command; then foo; else bar; fi should fullfil your needs.

But if for some reason you need to do more complex error handling, checking the value of $? would be more appropriate:

command
case $? in
  0) foo ;;
  1) bar ;;
  2) baz ;;
  *) something_else ;;
esac
5

According to the link you posted it should be something like this:

if pv --wait "$input_filename" | openssl enc -aes-256-cbc -d -salt -out "$output_filename"; then
        code for true
else
        code for false
fi

In my testing this may be an issue with pipelines depending on what is on the other end of yours...I think with openssl you should be fine but if you were piping to something like cat or echo I believe it will always be treated as success because the last command in the pipeline will exit with success.

If you just have one command to execute on success or on failure, something like this may also work:

command && code for success 

or

command || code for failure
3
  • 1
    Hmm, if in your last suggestion code for success fails, code for failure will be executed too. Definitely not the intended behavior. You need to be very careful with what commands are executed in code for success.
    – jlliagre
    Dec 9, 2017 at 17:03
  • @jlliagre, good catch thanks. I have modified it to use one or the other.
    – jesse_b
    Dec 9, 2017 at 17:06
  • 1
    yes, the exit status of a pipeline is the exit status of the last command, unless you use something like set -o pipefail (in bash, ksh etc).
    – ilkkachu
    Dec 10, 2017 at 10:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .