Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Create Parent Directories with Curl Using the --create-dirs Flag

blog/cards/create-parent-directories-with-curl-using-the-create-dirs-flag.jpg

This can save you from writing a file to a temporary directory and then moving it after using mkdir.

Quick Jump: Demo Video

Let’s say you want to download a file to a specific directory that doesn’t exist yet and also make it executable. I do this a lot with curl.

Not using --create-dirs:
curl https://raw.githubusercontent.com/nickjj/notes/master/notes \
  --output /tmp/notes \
  && chmod +x /tmp/notes \
  && mkdir -p /tmp/custom/dir/path \
  && mv /tmp/notes /tmp/custom/dir/path
Using --create-dirs:
curl https://raw.githubusercontent.com/nickjj/notes/master/notes \
  --create-dirs --output /tmp/custom/dir/path/notes \
  && chmod +x /tmp/custom/dir/path/notes

Since the last argument of the above command is the path of the file we can even improve on that by using $_ which contains the last argument of the previous command.

This way we can avoid duplicating the path without creating a custom variable:

curl https://raw.githubusercontent.com/nickjj/notes/master/notes \
  --create-dirs --output /tmp/custom/dir/path/notes \
  && chmod +x "${_}"

If any of the directories exist then they won’t be created but the command will still work. The directories get created with 0750 permissions.

--create-dirs has been available since curl 7.10.3 (January 2003).

Demo Video

Timestamps

  • 0:32 – Saving a file with curl
  • 1:15 – Saving a file to a directory that doesn’t exist, the hard way
  • 2:46 – Simplifying things with the –create-dirs flag
  • 3:39 – Using the shell to our advantage to make it better
  • 4:46 – If the directories exist, curl is smart enough to still work
  • 5:08 – This flag has been around for 20+ years

References

When did you learn about this flag? Let me know below!

Never Miss a Tip, Trick or Tutorial

Like you, I'm super protective of my inbox, so don't worry about getting spammed. You can expect a few emails per month (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments