What's wrong with this youtube-dl automatic script?

你离开我真会死。 提交于 2020-01-15 05:57:50

问题


first of all, I'm quite new with bash scripting and I'm just starting to learn, evidently there's something wrong with this script, but I don't know what it is...

I created a bash script to automate downloading videos with youtube-dl:

#!/bin/bash

echo url:
read url
export url
youtube-dl -f 'bestvideo[height<=360]+worstaudio/worst[height<=360]' $url

The idea is that I type in the command line the name of the script, e.g.: "360" and it will ask for a url (e.g.: a Youtube video), I paste it and youtube-dl downloads it with the stated parameters. It works like a charm...

Now, I want to make the script more complex and I think I need to convert the youtube-dl command to a variable (of course, being a newbie, I might be wrong, but let's assume I'm right for a moment...)

#!/bin/bash

video="youtube-dl -f 'bestvideo[height<=360]+worstaudio/worst[height<=360]'"

echo url:
read url
export url
$video $url

When I try this, it throws me an error: "ERROR: requested format not available " I don't know what's wrong... I'd like to solve the problem with the least changes to the code as possible and I repeat, I'd like to know what's wrong with the current code so I can learn from it.

Thank you very much in advance!


回答1:


It's explained in detail here here: I'm trying to put a command in a variable, but the complex cases always fail!

First always double-quote your variables, unless you know exactly what will happen if you don't.

You don't need to export that variable: you're not invoking any other program that needs to use it.

When you want to re-use a command, think about putting it in a function:

#!/bin/bash
function video {
    youtube-dl -f 'bestvideo[height<=360]+worstaudio/worst[height<=360]' "$1"
}
read -p "url: " url
video "$url"

Actually, I would do this:

  1. add that function to your ~/.bashrc,
  2. source that file: source ~/.bashrc
  3. then you can use it from the command line:

    video 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
    



回答2:


Remove the single quote from the -f parameter it will work.

For eg.

video="youtube-dl -f bestvideo[height<=360]+worstaudio/worst[height<=360]"


来源:https://stackoverflow.com/questions/54932941/whats-wrong-with-this-youtube-dl-automatic-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!