1

I've written a pretty basic script that let's me download a file using a URL. Here is my script:

#!/bin/sh

# A script that downloads a file based on url

function filedl() {
  echo "What is the url for the file?"
  read FILEURL
  wget $FILEURL
  echo "Download complete"
}

filedl

What I'd like to be able to do is target the downloaded file immediately after it's downloaded and automatically move it to a pre-defined directory using a further command or function in my script.

I have read a few threads about how to pipe an output to a variable but I can't work out how to do that with my script. These are the threads I've read:

I've tried to create a new variable with something like the following but it didn't seem to work:

NEWFILE=$(wget $FILEURL)

I also tried a variation of my script with this modification of the function call:

NEWFILE=$(filedl) <-- This also didn't seem to do anything.

Finally, I moved my commands out of a function and just listed each command with variations of the variable definition attempts I described above. I still couldn't figure out how to do this.

I'm still pretty new to shell scripting so apologies if I'm missing something that should be obvious.

2

Rather than capturing the file in a variable, unnecessarily putting the whole thing in memory, use wget's --output-document/-O flag and one of these two variations:

wget -O /path/to/file ... http://example.com/foobar
wget -O - ... http://example.com/foobar > /path/to/file

...where /path/to/file is any path+filename you desire. (And ... just represents any other flags or params you may be using.)

Or if you want to preserve the default name of the downloaded file use --directory-prefix or -P and just specify the directory to which the file should be saved.

wget -P /some/path ... http://example.com/foobar
  • Ok, that makes sense but, in this case, I'm happy to use the downloaded file's name. I just want to move it to another directory. The -O option, as I understand it, requires me to give it a new file name? – Paul Jacobson Dec 21 '17 at 9:13
  • Ok, I modified the line to this: wget --directory-prefix $FILEURL > ~/Downloads I got an error: ./file-dl.sh: line 8: /Users/pauljacobson/Downloads: Is a directory The download failed with both the -P and --directory-prefix options. – Paul Jacobson Dec 21 '17 at 9:25
  • wget --directory-prefix ~/Downloads $FILEURL – B Layer Dec 21 '17 at 9:25
  • Fantastic, that worked. Thank you very much. – Paul Jacobson Dec 21 '17 at 9:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.