I have made a bash script where I can stream a YouTube video with youtube-dl and play it with mplayer. I based it on this terminal command:
$ mplayer -ontop -cookies -cookies-file ./cookie.txt $(youtube-dl -gf 34 --cookies ./cookie.txt "https://www.youtube.com/watch?v=<VIDEO ID>")
Found here.
Manually inputting the video resolution and URL options for youtube-dl work fine. However I wanted to make a script that would make input easier so I would not have to remember the entire command every time I wanted to play a video.
The script:
#!/bin/bash
echo "Input YouTube ID (the string that follows 'http://www.youtube.com/watch?v='):"
echo ""
read video_id
echo ""
echo "Input Video Resolution (17=144, 5=240, 18=360, 35=480, 22=720, or 37=1080):"
echo ""
read resolution
first_string='mplayer -ontop -cookies -cookies-file ./cookie.txt $(youtube-dl -gf res --cookies ./cookie.txt "https://www.youtube.com/watch?v=VIDEO-ID")'
second_string="${first_string/VIDEO-ID/$video_id}"
last_string="${second_string/res/$resolution}"
$last_string
I have gotten the youtube-dl options to work fine with the string replacements I have set up. The problem happens when the Terminal tries to read the options related to youtube-dl giving me the output:
Unknown option on the command line: -gf
Error parsing option on the command line: -gf
MPlayer svn r34540 (Ubuntu), built with gcc-4.6 (C) 2000-2012 MPlayer Team
Removing -gf does not do much to help either, giving me the output:
Unknown option on the command line: --cookies
Error parsing option on the command line: --cookies
MPlayer svn r34540 (Ubuntu), built with gcc-4.6 (C) 2000-2012 MPlayer Team
I'm not sure why manually typing/copy-pasting the command works just fine with -gf and --cookies, but does not work well with a bash script. I am using Elementary OS 0.2 Luna 64 bit (based on Ubuntu 12.04 LTS), with Linux kernel 3.2.057-generic, and Bash 4.2.25. Any insight would be greatly appreciated.
The problem is with the definition of first_string
. Single quotes prevent parameter expansion which will stop the youtube-dl
command running in a subshell.
Rather than constructing a string for the shell to execute, it would be a better idea to run the desired command with the correct parameters. Immediately after reading from the prompts:
mplayer -ontop -cookies -cookies-file ./cookie.txt $(youtube-dl -gf "$resolution" --cookies ./cookie.txt "https://www.youtube.com/watch?v=${video_id}")