簡體   English   中英

檢查 wget/curl 是否存在

[英]Check for existence of wget/curl

嘗試執行腳本以使用 wget 下載文件,或者如果 wget 在 Linux 中不存在,則使用 curl。 我如何讓腳本檢查 wget 的存在?

Linux 有一個which命令將檢查您的路徑上是否存在可執行文件:

pax> which ls ; echo $?
/bin/ls
0

pax> which no_such_executable ; echo $?
1

如您所見,它設置了返回碼$? 輕松判斷是否找到了可執行文件。

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

還可以使用commandtypehash來檢查 wget/curl 是否存在。 這里的另一個線程 - “ 從 Bash 腳本檢查程序是否存在”很好地回答了在 bash 腳本中使用什么來檢查程序是否存在。

我會這樣做 -

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

首先要做的是嘗試 install 以使用您常用的包管理系統安裝wget 它應該告訴你是否已經安裝;

yum -y wget

否則只需啟動如下命令

wget http://download/url/file 

如果您沒有收到任何錯誤,那么就可以了。

取自 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

解釋:它查找wget的位置並檢查那里是否存在文件,如果存在,則執行腳本友好(即安靜)下載。 如果未找到 wget,它會以類似的腳本友好方式嘗試curl

(請注意,該問題並未指定 BASH,但我的回答是假設它。)

只需運行

wget http://download/url/file 

您將看到端點是否可用的統計信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM