3

I have written some code for downloading favicons. It has a logical error which I am not able to see.

#!/bin/bash
ico="1";
if [[ $ico =~ ^-?[0-9]+$ ]]; then
wget -P $HOME/Downloads/ http://www.google.com/favicon.ico
elif [[ $ico -eq 1 ]]; then 
wget -P $HOME/Downloads/ http://www.cnet.com/favicon.ico
elif [[ $ico -eq 3 ]]; then
wget -P $HOME/Downloads/ https://www.facebook.com/favicon.ico
else
wget -P $HOME/Downloads/ https://www.twitter.com/favicon.ico
fi

According to my logic, when the variable ico is 1 it should download favicons from both Google and CNet, as it satisfies both conditions (it is an integer and it has the value of 1). However, it only downloads Google’s favicon, not CNet’s.

1 Answer 1

9

if..elif..else will only trigger one clause. elif is short for "else if" so, like else, relies on previous checks not activating.

If you want to evaluate each condition separately so that more than one can be called, each needs to be its own if. We'd also be able to do away with the else (that will always be called):

#!/bin/bash
ico="1";

if [[ $ico =~ ^-?[0-9]+$ ]]; then
    wget -P $HOME/Downloads/ http://www.google.com/favicon.ico
fi

if [[ $ico -eq 1 ]]; then 
    wget -P $HOME/Downloads/ http://www.cnet.com/favicon.ico
fi

if [[ $ico -eq 3 ]]; then
    wget -P $HOME/Downloads/ https://www.facebook.com/favicon.ico
fi

wget -P $HOME/Downloads/ https://www.twitter.com/favicon.ico

On reflection, you might want something like this:

#!/bin/bash
ico="1";

if [[ $ico =~ ^-?[0-9]+$ ]]; then
    if [[ $ico -eq 1 ]]; then 
        wget -P $HOME/Downloads/ http://www.cnet.com/favicon.ico
    elif [[ $ico -eq 3 ]]; then
        wget -P $HOME/Downloads/ https://www.facebook.com/favicon.ico
    else
        wget -P $HOME/Downloads/ http://www.google.com/favicon.ico
    fi
else
    wget -P $HOME/Downloads/ https://www.twitter.com/favicon.ico
fi

It first checks the input is a numeral. If it is and it's 1, cnet. If it's 2, facebook. If it's another number, google. If it isn't a number, twitter.

It's a bit weird trying to infer what you want from an abstract problem like this, but that makes the most sense to me.

3
  • it has one problem it will also downloads twitters favicon which i dont want for my ico condition ie 1
    – potholiday
    Jun 16, 2015 at 7:48
  • 2
    So change it again to do what you want. You hadn't explained exactly what you want so I was merely providing an example.
    – Oli
    Jun 16, 2015 at 7:57
  • K understood have to use a global if statement for integers? thanks Oli
    – potholiday
    Jun 16, 2015 at 8:12

You must log in to answer this question.

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