Bash 脚本执行 wget 并在其中包含变量

问题描述 投票:0回答:4

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

#!/bin/bash

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

echo $(date) 'Running wget...'
wget -O - -q "$URL/something/something2"
linux bash
4个回答
8
投票

四件事:

  1. 在您的网址周围添加引号: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}"

1
投票

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


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

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


0
投票

Bash(或其他 shell)中的另一个方便的选项是创建一个简单的辅助函数,该函数使用几乎所有站点所需的通用选项以及您通常使用的任何特定选项来调用

wget
。这减少了所涉及的输入,并且在您的脚本中也很有用。我将以下内容放在 ~/.bashrc 中,以使其可供所有 shell/子 shell 使用。它验证输入,检查
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
的另一种方法。


0
投票

对于 Kaggle 笔记本:

url = "https://google.com"
name = "file.f"
!wget "$url" -O "$name"
© www.soinside.com 2019 - 2024. All rights reserved.