2017-10-11 246 views
3

我正在編寫一個bash腳本來下載imgur相冊或學習bash。我有這麼多的書面,但當我運行它我得到這個輸出:Bash腳本「命令未找到錯誤」

Enter the URL of the imgur album you would like to download: imgur.com 
./imgur_dl.sh: line 25: Validating: command not found 
./imgur_dl.sh: line 26: Getting: command not found 
./imgur_dl.sh: line 30: imgur.com: command not found 

這是我的代碼到目前爲止。

#!/bin/bash 

url="" 
id="" 

get_id(){ 
    echo "Getting Album ID..." 
    local url=$1 
    echo $url 
    echo "Successflly got Album ID..." 
    return 
} 

validate_input(){ 
    echo "Validating Input..." 
    local id=$1 
    echo $id 
    echo "Input Validated Successfully..." 
    return 
} 

get_input(){ 
    read -p "Enter the URL of the imgur album you would like to download: " url 
    echo $url 
    $(validate_input url) 
    $(get_id url) 
    return 
} 

$(get_input) 

我在做什麼錯,或者我沒有得到什麼? 我在macOS上工作,它有所幫助。

+1

參見[命令替換(https://en.wikipedia.org/wiki/Command_substitution)。 – nobar

回答

2

只需直接調用的功能,如:

valide_input $url

等。

#!/bin/bash 

    url="" 
    id="" 

    get_id() 
    { 
     echo "Getting Album ID..." 
     local url=$1 
     echo $url 
     echo "Successflly got Album ID..." 
     return 
    } 

    validate_input() 
    { 
     echo "Validating Input..." 
     local id=$1 
     echo $id 
     echo "Input Validated Successfully..." 
     return 
    } 

    get_input() 
    { 
     read -p "Enter the URL of the imgur album you would like to d  ownload: " url 
     echo $url 
     validate_input $url 
     get_id $url 
     return 
    } 

    get_input 

而且,別人的建議,你可以通過把$ URL雙引號中這更好的,像

validate_input "$url"

因此,否則處理無效的網址。

+0

用四個空格前綴代碼/數據。請看[編輯幫助](http://stackoverflow.com/editing-help)。 – Cyrus

+0

感謝賽勒斯。任何快速的方法來立即格式化一個塊? – imerso

+0

突出顯示代碼,然後單擊「代碼示例」按鈕。 – nobar

2

此語法意味着,執行的get_id url輸出作爲外殼命令

$(get_id url) 

在當前實現的get_id url輸出是這樣的:

Getting Album ID... 
url 
Successflly got Album ID... 

這得到作爲shell命令執行, 生成錯誤消息:

./imgur_dl.sh: line 26: Getting: command not found 

因爲確實沒有這樣的shell命令 「獲取」。


我想你想要做這樣的事情:

local id=$(get_id "$url") 

get_id是一個函數,它接受一個URL並使用該URL得到一些ID,然後echo該id。 函數應該是這個樣子:

get_id() { 
    local url=$1 
    local id=... 
    echo id 
} 

即:

  • 您需要刪除其他echo語句像echo "Getting ..."東西
  • 你需要真正實現獲得一個ID,因爲函數目前不這樣做。

其他功能也一樣。


這裏的東西,讓你開始:更多的情況下

#!/bin/bash 

is_valid_url() { 
    local url=$1 
    # TODO 
} 

input_url() { 
    local url 
    while true; do 
     read -p "Enter the URL of the imgur album you would like to download: " url 
     if is_valid_url "$url"; then 
      echo "$url" 
      return 
     fi 
     echo "Not a valid url!" >&2 
    done 
} 

download() { 
    local url=$1 
    echo "will download $url ..." 
    # TODO 
} 

main() { 
    url=$(input_url) 
    download "$url" 
} 

main 
+0

正確的解決方案,但不是[命令替換](https://en.wikipedia.org/wiki/Command_substitution)的技術準確描述。 – nobar