How to download YouTube videos from the command line

Ever needed to download a video from YouTube (or a similar site) and had to resort to using a shady site to do it? Well now you don’t need to.

youtube-dl

Install youtube-dl, a command line utility that can download video/audio from YouTube, Vimeo, DailyMotion, CollegeHumor, SoundCloud, MTV, & more.

Command to install youtube-dl
1
$ sudo pip install --upgrade youtube_dl

Then, to download a video from YouTube, all you need to do is run:

Command to download a YouTube video
1
$ youtube-dl "https://www.youtube.com/watch?v=wNRXFqh36oo"

Same thing for Vimeo, SoundCloud, MTV, and many other sites:

Command to download videos from other sites
1
2
3
$ youtube-dl "http://vimeo.com/2143576"
$ youtube-dl "https://soundcloud.com/piercefulton/pierce-fulton-mixify-set"
$ youtube-dl "http://www.mtv.com/videos/true-life-im-saving-detroit/1711609/playlist.jhtml#series=2211&seriesId=5232&channelId=1"

Convert a YouTube video directly to MP3

Now let’s say that you want to convert that YouTube video directly to an MP3 file, instead of saving it as an MP4 video. All you need to do is install youtube-dl-mp3.

Make sure you have the following installed and working first:

  • youtube-dl
  • wget
  • ffmpeg
  • lame

Then, simply copy and paste the following code to your $PATH in /usr/local/bin and name it youtube-dl-mp3:

youtube-dl-mp3 code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/bin/bash
url=$1
path=$2
TMP_FILE="youtube-mp3-$RANDOM.tmp"
youtube-dl --ignore-errors --get-title --get-url --get-filename "$url" > $TMP_FILE 2> "/tmp/$TMP_FILE.err"
exec 42< $TMP_FILE
while read video_title <&42 ; do
read video_url <&42
read video_filename <&42
wget "$video_url" -O "$video_filename"
ffmpeg -i "$video_filename" "$video_filename.wav"
if [ -z "$path" ]; then
lame "$video_filename.wav" "$video_title.mp3"
else
lame "$video_filename.wav" "$path/$video_title.mp3"
fi
rm -f "$video_filename" "$video_filename.wav"
done
exec 42<&-
rm -f $TMP_FILE

Now, to download a YouTube video and convert it directly to MP3, just run the following:

Command to download a YouTube video and convert to MP3
1
$ youtube-dl-mp3 "https://www.youtube.com/watch?v=wNRXFqh36oo"