bash scripting: youtube downloading macro

Summary
<p>
    Once again, the command line is the root of all that is good in the world. This time, it has helped improve on a long-standing issue for me: what is the easiest way to get a copy of all the <a href='http://www.youtube.com/playlist?list=PLmku2swCXQpqWAZSscjV4h9bcLennVcif' target='_blank'>luscious melodies</a> i hear on youtube? Courtesy of <a href='http://rg3.github.io/youtube-dl/' target='_blank'>youtube-dl</a>, a nifty little command line utility, this problem has been solved. However, every once in awhile it throws errors and i wanted a wrapper bash script to take care of this and some other processing. I'll briefly go over the code.
</p>

Once again, the command line is the root of all that is good in the world. This time, it has helped improve on a long-standing issue for me: what is the easiest way to get a copy of all the luscious melodies i hear on youtube? Courtesy of youtube-dl, a nifty little command line utility, this problem has been solved. However, every once in awhile it throws errors and i wanted a wrapper bash script to take care of this and some other processing. I'll briefly go over the script (scroll to end of article to see full code).

The script solves three basic problems: re-running youtube-dl after errors, automatically deciding whether input is a list of links or a single URL, and formatting the output files. Formatting the music output files was the easiest: a base command was stored in a variable (baseCmd) that contains formatting for the title and extension (%(title)s.%(ext)s) as per the youtube-dl documentation.

Automatically choosing to run youtube-dl against a single or multiple URLs involved detecting http:// in the input and modifying the baseCmd variable from there. I avoided using getopts this time around to parse input arguments as the script was supposed to be simple as possible; i'll add this standardized input style in future revisions.

Handling errors involved taking advantage of the tee command. The main reason for using tee was to show the user output while also writing all the output from the shell to a file. After the command had finished running, successfully or not, I then grep the output, checking for ERROR, which youtube-dl outputs on error. The double passing of tee allows me to capture both STDOUT and STDERR, else just STDOUT would never capture the thrown errors and the program would exit even when problems arise. The script then calls itself passing the original argument (the base case for the recursion is the lack of an error...).

This should prove useful for people who want a little script to automate some parts of using this incredibly useful tool.

youtube.sh wrapper script
Bash
  1. # /bin/bash
  2.  
  3. # biafra ahanonu
  4. # updated: 2013.05.05
  5. # youtube-dl wrapper script to help handle errors and automate some things
  6.  
  7. printHelp(){
  8.         echo "youtube.sh FILE ARG
  9.         ARG can be:
  10.                 -h for help
  11.                 -a for list of youtube URLs in a file, use only if filename contains 'http://'
  12.                 empty for single URL or file (auto-detects)"
  13.         exit 0
  14. }
  15.  
  16. # help string
  17. helpString='-h -help --h --help'
  18. # check if first argument contains a URL
  19. URLcheck=$(echo $1 | grep 'http://' | wc -l)
  20. # base command to use
  21. baseCmd="youtube-dl -ixko %(title)s.%(ext)s --no-post-overwrites --verbose --restrict-filenames --audio-format m4a -R 30 "
  22.  
  23. # check if first argument is a help string
  24. if [[ "$helpString" == *"$1"* ]]; then
  25.         printHelp
  26. fi
  27.  
  28. # check if second arg is empty
  29. if [ -z "$2" ]; then
  30.         # If contains URL, do normally
  31.         if [ $URLcheck -eq 0 ]; then
  32.                 cmd=$baseCmd"-a $1"
  33.         # Enter batch mode if first arg is not URL
  34.         elif [ ! $URLcheck -eq 0 ]; then
  35.                 cmd=$baseCmd"$1"
  36.         fi
  37. # User should flag with -a
  38. elif [ $2 == -a ]; then
  39.         cmd=$baseCmd"-a $1"
  40. fi
  41.  
  42. echo $cmd
  43.  
  44. # continue until no error encountered
  45. error=1
  46. while [ $error -eq 1 ]; do
  47.         # clear output file
  48.         echo '' > youtube.output
  49.         # save to file and output to cmd line, captures STDOUT and STDERR to allow restart of script if errors
  50.         # $cmd | tee -ai youtube.output
  51.         $cmd > >(tee -ai youtube.output) 2> >(tee -ai youtube.output >&2)
  52.         # check if an error occurred, if so, restart script to resume download
  53.         if [ $(grep 'ERROR' youtube.output | wc -l) -eq 0 ]; then
  54.                 echo No errors found, exiting...
  55.                 error=0
  56.         else
  57.                 echo ________________________________________________________
  58.                 echo Errors found, restarting script...
  59.                 bash youtube.sh $1
  60.         fi
  61. done

-biafra
bahanonu [at] alum.mit.edu

other entires to explore:

facebook crawler and youtube api: part 1
07 october 2012 | programming

Created a small app, implemented in python and PHP, that crawls authenticated Facebook page for Youtube videos and adds them to a specified[...] user's Youtube playlist. Useful for groups that post a lot of youtube videos and want a centralized playlist to share with others. I'll go over some of the implementation details in this post.

week 1 | go time
12 june 2012 | singapore

Wow, what a week. Ran around Hong Kong, learned a couple new things in the lab, meet a bunch of awesome MIT/SUTD students, went clubbing tw[...]ice, ate a different type (Indian, Indonesian, Muslim, etc.) of food each meal, wandered around Singapore several of the nights and so much more. To top it all off, I was able to learn a ton about Singapore's culture. This place is awesome.

humanity's gold
20 november 2009 | short story

Captain’s Log 1.25.2838 My eyes watered at the sight. We had finally discovered what we had spent all these years wandering[...] aimlessly for. Shifting and moving, the silvery substance coated the land, its beauty enticing and dicing. There were several who ventured over its smooth surface, dying one by one. Out in the distance could be seen the splendorous pinnacle, atop its peak a mountain of gold. Men still strove for that most holy of materials, still killed and maimed for a chance to hold and possess it; some said that gold had become more than a sign of wealth and power.

Another story that ended up inspiring my book-in-progress Filugori, it is a focus on humanity's lust for something, anything, that will bring him fame and glory. It uses a character more obsessed with the adventure as a counter-backdrop to the drama unfolding around him.

©2006-2024 | Site created & coded by Biafra Ahanonu | Updated 17 April 2024
biafra ahanonu