Toshi
Toshi

Reputation: 6340

returns the exact returned value if wget fails

I'd love to return the exact value if wget command fails in efficient way without changing it.

Can exit #? output the returned value from wget?

Ex.

# If it succeeds, then wget returns zero instead of non zero
## 0    No problems occurred.
## 1    Generic error code.
## 2    Parse error—for instance, when parsing command-line options, the ‘.wgetrc’ or ‘.netrc’...
## 3    File I/O error.
## 4    Network failure.
## 5    SSL verification failure.
## 6    Username/password authentication failure.
## 7    Protocol errors.
## 8    Server issued an error response.
wget https://www.google.co.jp/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png -o test.img
if [ $? -ne 0 ]
then
    # exit 16 # failed ends1 <== This doesn't tell anything
    exit #?
fi

Upvotes: 0

Views: 2998

Answers (2)

Toby Speight
Toby Speight

Reputation: 30911

The -e option of Bash may do what you want:

Exit immediately if a pipeline (which may consist of a single simple command), a list, or a compound command (see SHELL GRAMMAR), exits with a non-zero status.

It's also important to know that

Bash's exit status is the exit status of the last command executed in the script.

My experiments with Bash 4.4 suggest that the exit status of the failing command is returned, even if a trap handler is invoked:

$ ( trap 'echo $?' ERR; set -e; ( exit 3 ) ; echo true ) ; echo $?
3
3

So you can write:

#!/bin/bash

url=https://www.google.co.jp/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png

set -e
wget -o test.img "$url"
set +e    # if you no longer want exit on fail

For just one command in your script, you might prefer an explicit test and exit like this:

wget -o test.img "$url"  || exit $?

Further, exit with no argument is the same as exit $?, so that can be simplified to just

wget -o test.img "$url"  || exit

Upvotes: 1

Vicente Olivert Riera
Vicente Olivert Riera

Reputation: 1220

wget https://www.google.co.jp/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png -o test.img
# grab wget's exit code
exit_code=$?
# if exit code is not 0 (failed), then return it
test $exit_code -eq 0 || exit $exit_code

Upvotes: 2

Related Questions