Score:1

How to use wget http status codes in an if else statement to take an action based on the status code

fk flag

I'm writing a script that is downloading a bunch of files, I'm using wget to download the file and I want to echo back to the terminal custom status messages for each file based on 3 scenarios:

  1. Files downloaded successfully (HTTP/1.1 200 OK)
  2. Files did not change from the one locally (HTTP/1.1 304 Not Modified)
  3. Anything else is a failed download

I'm able to get the status code and use awk to isolate just the status code number(200, 304, etc) I have the following to pull out the HTTP status:

#!/bin/bash
wget -NS http://ipv4.download.thinkbroadband.com/5MB.zip 2>&1 | grep "HTTP/" | awk '{print $2}'

if [ $? = 200 ]; then
echo "File downloaded
"
if [ $? = 304 ]; then
echo "File not modified from local copy"
else
    echo "Something went wrong"
    exit 1
fi

But this just prints the http status code back to the terminal, and always returns that last else statement.

laptop:~$ ./test.sh
304
Something went wrong

How do I send the output to run through an if else statement?

djdomi avatar
za flag
usually you should use elif to go through in once, else you break up the if else chain
Score:1
jp flag

You are printing the HTTP status code to the standard output but your code compares a return code from wget, not a value printed to standard output. If there is no error then wget returns 0.

corefile avatar
fk flag
right - how can I print the HTTP status code to standard output and use in the if statement
Score:0
ru flag

Your script needs to capture the output of the first command. There may be a more elegant approach, but the basic form:

wget_result="$(wget -NS http://ipv4.download.thinkbroadband.com/5MB.zip 2>&1|grep "HTTP/"|awk '{print $2}')"

if [ $wget_result = 200 ]; then
echo "File downloaded
"
if [ $wget_result = 304 ]; then
echo "File not modified from local copy"
else
    echo "Something went wrong"
    exit 1
fi
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.