Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get CURL to save to a different directory?

Tags:

bash

curl

I need to be able to pass in the URL of the file download, plus a path for the file to be saved to.

I think it has something to do with -O and -o on CURL, but I can't seem to figure it out.

For example, this is what I'm using in my bash script now:

#!/bin/sh

getsrc(){
    curl -O $1
}

getsrc http://www.apache.org/dist/ant/binaries/apache-ant-1.7.1-bin.tar.gz

How can I change the curl statement so I can do

getsrc http://www.apache.org/dist/ant/binaries/apache-ant-1.7.1-bin.tar.gz /usr/local

and have it save the file to /usr/local?

like image 962
Geuis Avatar asked Apr 09 '09 23:04

Geuis


2 Answers

If this is to be a script, you should make sure you're ready for any contingency:

getsrc() {
    ( cd "$2" && curl -O "$1" )
}

That means quoting your parameters, in case they contain shell metacharacters such as question marks, stars, spaces, tabs, newlines, etc.

It also means using the && operator between the cd and curl commands in case the target directory does not exist (if you don't use it, curl will still download without error but place the file in the wrong location!)

That function takes two arguments:

  • The URL to the data that should be downloaded.
  • The local PATH where the data should be stored (using a filename based off of the URL)

To specify a local filename rather than a path, use the more simplistic:

getsrc() {
    curl "$1" > "$2"
}
like image 194
lhunath Avatar answered Oct 15 '22 06:10

lhunath


Hum... what you probably want to do is

getsrc(){
    ( cd $2 > /dev/null ; curl -O $1 ; ) 
}

The -O (capital O) says to store in a local named like the remote file, but to ignore the remote path component. To be able to store in a specific directory, the easiest way is to cd to it... and I do that in a sub-shell, so the dir change does not propagate

like image 21
Varkhan Avatar answered Oct 15 '22 04:10

Varkhan