繁体   English   中英

Bash 脚本执行 wget,其中包含一个变量

[英]Bash script execute wget with a variable inside it

我正在尝试执行一个带有变量的 wget 命令,但它只是忽略了它,知道我做错了什么吗?

#!/bin/bash

URL=http:://www.myurl.com

echo $(date) 'Running wget...'
wget -O - -q "$URL/something/something2"

四件事:

  1. 在您的 URL 周围添加引号:http://www.myurl.com ==> "http://www.myurl.com"
  2. 去掉双冒号:“http://www.myurl.com”==>“ http://www.myurl.com
  3. 去掉 wget 命令上的额外标志和连字符: "wget -O - -q "$URL/something/something2"" ==> wget "$URL/something/something2"
  4. 在变量周围添加花括号: "wget "$URL/something/something2"" ==> "wget "${URL}/something/something2""

这有效:

#!/bin/bash

URL="http://www.google.com"

echo $(date) 'Running wget...'
wget "${URL}"

Bash(或其他 shell)中的另一个方便的选项是创建一个简单的辅助函数,该函数使用几乎所有站点所需的通用选项和您通常使用的任何特定选项调用wget 这减少了所涉及的输入,并且在您的脚本中也很有用。 我将以下内容放在我的 ~/.bashrc 中,使其可用于所有 shells/subshel​​ls。 它验证输入,检查wget是否可用,然后使用脚本中设置的默认选项将所有命令行参数传递给wget

wgnc () {
    if [ -z $1 ]; then
        printf "  usage:  wg <filename>\t\t(runs wget --no-check-certificate --progress=bar)\n"
    elif ! type wget &>/dev/null; then
        printf "  error: 'wget' not found on system\n"
    else
        printf "  wget --no-check-certificate --progress=bar %s\n" "$@"
        wget --no-check-certificate --progress=bar "$@"
    fi
}

您可以通过进一步为函数设置别名来进一步减少输入。 我用:

alias wg='wgnc'

这将正常的wget --no-check-certificate --progress=bar URL到简单的wg URL 显然,您可以设置选项以满足您的需要,但这是在脚本中使用wget的另一种方式。

我在 IPython (colab) 中使用该代码:


URL = 'http:://www.myurl.com'
!wget {URL}

我写这个答案是因为正在搜索它!)

暂无
暂无

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

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