Bash 脚本"Command Not Found Error"



我正在编写一个bash脚本来下载imgur专辑或学习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 上工作,它完全有帮助。

只需直接调用函数,例如:

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"

因此,它会处理其他无效的 URL。

此语法表示,执行 get_id url as shell 命令的输出

$(get_id url)

在当前的实现中,get_id url的输出是这样的:

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

这作为 shell 命令执行,生成错误消息:

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

因为确实没有这样的外壳命令"Getting"。


我想你想做这样的事情:

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

最新更新