1. #!/bin/bash
  2. #############################################################
  3. #   Script to download all images in an imgur.com album
  4. #   to disk.
  5. #   USAGE: ./imgur.sh http://imgur.com/a/id
  6. #############################################################
  7.  
  8. ## We do not need to set url to ''
  9.  
  10. ## With unique tempfiles, multiple instances can run simuntaneously
  11. tf=$(mktemp .imgur.XXXXX)
  12.  
  13. url=$1
  14. ## A separate usage is nice, but is is used only once: embed it into the if
  15. if [[ -z $url ]]; then
  16.   echo -e "Imgur Album downloader\nUsage: $0 <album url>"
  17.   exit 1
  18. fi
  19.  
  20. if [[ "$url" =~ "imgur.com/a/" ]]; then
  21.   ## We have no special need for curl; wget is AFAIK more often preinstalled
  22.   wget -q -O "$tf" "$1"
  23.   #title=$(awk -F \" '/data-cover/ {print $6; exit}' $ass)
  24.   ## I don't know enough about awk to speak of it, but regex is nice:
  25.   title=$(grep -Po '(?<=data-title=").*?(?=" )' "$tf") # A lookabehind, nongreedy and ending lookahead
  26.   albumid=$(grep -Po '(?<=id="album-).{5}(?=")' "$tf") # Ids are 5 chars
  27.   if [[ -z $title ]]; then
  28.     #title=$(awk -F \" '/data-cover/ {print $8}' $ass)
  29.     ## data-cover can also be something like LPzCFb.jpg, so...
  30.      # Let's just use the album id
  31.     title=$albumid
  32.   fi
  33.     title=${title// /_}
  34.     dir="${title//[^a-zA-Z0-9_]/}"
  35.   if [[ -d $dir ]]; then
  36.     echo "Directory '$dir' already exists, you may have downloaded this album before."
  37.     exit 1
  38.   fi
  39.   ## Else is unneeded
  40.   ## Worst case: Using the album id, the dirname should never be empty
  41.   if [[ -z $dir ]]; then
  42.     title=$albumid
  43.   fi
  44.   echo "Saving to '$dir'"
  45.   mkdir -p $dir
  46.  
  47.   #for image in $(awk -F \" '/data-src/ {print $10}' $ass | sed /^$/d | sed s/s.jpg/.jpg/); do
  48.   ## Some images are so big they won't be displayed fully. With this we get full links!
  49.   for image in $(grep -Po '(?<=a href=")http://i\.imgur.*?(?=")' "$tf"); do
  50.     #filename=$(sed s/http:\\/\\/i.imgur.com\\/// <<< $image)
  51.     #...
  52.     #fi
  53.     ## We don't need to guess the filetype nor create the name, wget handles that (<<< is neat though)
  54.     echo -n "Downloading '$image'..."
  55.     wget -q -nc -P "$dir" "$image" # -P will set directory prefix, -nc won't overwrite
  56.     if [ "$?" = "0" ]; then echo " Done."; else echo "Failed.."; fi
  57.   done
  58. fi
  59.  
  60. ## No need to tell the user about tempfiles
  61. rm "$tf"
  62. echo "All done!"
  63. #exit 0