Trying to do a script to download a file using wget, or curl if wget doesn't exist in Linux. How do I have the script check for existence of wget?
6 Answers
Linux has a which
command which will check for the existence of an executable on your path:
pax> which ls ; echo $?
/bin/ls
0
pax> which no_such_executable ; echo $?
1
As you can see, it sets the return code $?
to easily tell if the executable was found, so you could use something like:
if which wget >/dev/null ; then
echo "Downloading via wget."
wget --option argument
elif which curl >/dev/null ; then
echo "Downloading via curl."
curl --option argument
else
echo "Cannot download, neither wget nor curl is available."
fi

- 854,327
- 234
- 1,573
- 1,953
-
1If someone would just want the exit code one could only use `which ls 1&>1; echo $?` – r4d1um Jan 17 '19 at 21:02
wget http://download/url/file 2>/dev/null || curl -O http://download/url/file

- 3,820
- 1
- 21
- 23
-
1Note that for this answer, if the user has both wget and curl installed, then this will also run curl if wget fails (for example, the file 404'd.) – alexyorke Mar 13 '21 at 04:48
One can also use command
or type
or hash
to check if wget/curl exists or not. Another thread here - "Check if a program exists from a Bash script" answers very nicely what to use in a bash script to check if a program exists.
I would do this -
if [ ! -x /usr/bin/wget ] ; then
# some extra check if wget is not installed at the usual place
command -v wget >/dev/null 2>&1 || { echo >&2 "Please install wget or set it in your path. Aborting."; exit 1; }
fi
-
good solution, thanks for linking to the other thread about `command` as well, helpful info, thank you! – kjones Apr 07 '19 at 03:37
First thing to do is try install to install wget
with your usual package management system,. It should tell you if already installed;
yum -y wget
Otherwise just launch a command like below
wget http://download/url/file
If you receive no error, then its ok.

- 8,193
- 15
- 41
- 69

- 8,097
- 2
- 17
- 20
A solution taken from the K3S install script (https://raw.githubusercontent.com/rancher/k3s/master/install.sh)
function download {
url=$1
filename=$2
if [ -x "$(which wget)" ] ; then
wget -q $url -O $2
elif [ -x "$(which curl)" ]; then
curl -o $2 -sfL $url
else
echo "Could not find curl or wget, please install one." >&2
fi
}
# to use in the script:
download https://url /local/path/to/download
Explanation:
It looks for the location of wget
and checks for a file to exist there, if so, it does a script-friendly (i.e. quiet) download. If wget isn't found, it tries curl
in a similarly script-friendly way.
(Note that the question doesn't specify BASH however my answer assumes it.)
Simply run
wget http://download/url/file
you will see the statistics whether the endpoint is available or not.

- 4,280
- 8
- 40
- 62