简体   繁体   English

检查 wget/curl 是否存在

[英]Check for existence of wget/curl

Trying to do a script to download a file using wget, or curl if wget doesn't exist in Linux.尝试执行脚本以使用 wget 下载文件,或者如果 wget 在 Linux 中不存在,则使用 curl。 How do I have the script check for existence of wget?我如何让脚本检查 wget 的存在?

Linux has a which command which will check for the existence of an executable on your path: Linux 有一个which命令将检查您的路径上是否存在可执行文件:

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.轻松判断是否找到了可执行文件。

wget http://download/url/file 2>/dev/null || curl -O  http://download/url/file

One can also use command or type or hash to check if wget/curl exists or not.还可以使用commandtypehash来检查 wget/curl 是否存在。 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.这里的另一个线程 - “ 从 Bash 脚本检查程序是否存在”很好地回答了在 bash 脚本中使用什么来检查程序是否存在。

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

First thing to do is try install to install wget with your usual package management system,.首先要做的是尝试 install 以使用您常用的包管理系统安装wget 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.如果您没有收到任何错误,那么就可以了。

A solution taken from the K3S install script (https://raw.githubusercontent.com/rancher/k3s/master/install.sh )取自 K3S 安装脚本的解决方案 (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 (ie quiet) download.解释:它查找wget的位置并检查那里是否存在文件,如果存在,则执行脚本友好(即安静)下载。 If wget isn't found, it tries curl in a similarly script-friendly way.如果未找到 wget,它会以类似的脚本友好方式尝试curl

(Note that the question doesn't specify BASH however my answer assumes it.) (请注意,该问题并未指定 BASH,但我的回答是假设它。)

Simply run只需运行

wget http://download/url/file 

you will see the statistics whether the endpoint is available or not.您将看到端点是否可用的统计信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM