tags:

views:

493

answers:

2

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?

+2  A: 

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

Varkhan
Hey that worked perfectly! Thanks for such a quick response.
Geuis
+1  A: 

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"
}
lhunath