[英]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
还可以使用command
或type
或hash
来检查 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.