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!
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:
source ~/.bashrc
then you can use it from the command line:
video 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'