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

additional articles to journey through:

quicklinks
29 may 2012 | programming

The new-tab page on most browsers inefficiently uses screen real estate by giving each website a picture and large button. While useful for[...] tablets, it prevents addition of many websites and can't be organized into groups without increasing the number of clicks required. Also, often only one search site is accessible, with the rest found in a drop-down menu. To alleviate this, I created quicklinks. It uses javascript to create a row of categories (that you choose), which when hovered over show associated links. Further, there are several search bars readily avaliable, no extra clicking needed. Enjoy.

Jill Stein Campaign Poster 2016 No. 1
18 October 2016 | designs

Presidential election 2016 poster no 11! Completing the major candidates set. Even if one doesn't agree with all of her posi[...]tions or worldview, it is worth listening to Dr. Stein's speeches and interviews along with evaluating her stances in greater detail. Might come away with a new idea or two.

reading list and book mini-reviews
21 may 2014 | books

Below is the current crop of books I'm reading along with ratings and mini-reviews for other novels I've recently finished. I'm always exci[...]ted to start a new book, so recommendations are welcome!

NOTE! The ratings are a combination of how impactful the book was on my thinking about a particular topic or how well I think it was written/got its point across. Thus, at times whether I agree or disagree with the content/thesis/etc. of the book, it could still get 5 stars if the point it makes gets me to think about the subject in a new way or changes how I interpret the world around me.

global history of architecture
08 june 2013 | architecture

One of my favorite classes at MIT was 4.605 (Global History of Architecture), which explored various styles and themes found throughout dif[...]ferent buildings and other types of architecture from the beginning of civilization to the present. In the spirit of sharing my enthusiasm for the course i'll discuss some takeaways from, and have included a couple papers i wrote for, the class.

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