问题
I'm trying to provide some kind of a GUI for wget download process by using zenity/yad. I have come up with this:
wget http://example.com/ 2>&1 | \
sed -u 's/^[a-zA-Z\-].*//; s/.* \{1,2\}\([0-9]\{1,3\}\)%.*/\1\n#Downloading... \1%/; s/^20[0-9][0-9].*/#Done./' | \
zenity --progress --percentage=0 --title=Download dialog --text=Starting... --auto-close --auto-kill
Now, suppose wget runs into an error. I need to inform the user that the download failed. Since the $?
variable seems to have a value of 0
regardless of success or failure (perhaps because $?
is storing zenity's exit status?), I can't tell if the download failed or succeeded.
How can I rectify the above described problem?
回答1:
You can say:
set -o pipefail
Saying so would cause $?
to report the exit code of the last command in the pipeline to exit with a non-zero status.
Quoting from The Set Builtin:
pipefail
If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default.
Additionally, the array PIPESTATUS
would report the return code of all the commands in the pipeline. Saying:
echo "${PIPESTATUS[@]}"
would list all those. For your example, it'd display 3 numbers, e.g.
1 0 0
if wget
failed.
Quoting from the manual:
PIPESTATUS
An array variable (see Arrays) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).
来源:https://stackoverflow.com/questions/21182937/combining-wget-and-zenity-yad