簡體   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