≡ Menu

How Do I ftp and Download files from a UNIX Shell Script

Question: I would like to execute ftp from inside a shell script. I would also like to provide the username and password required for the FTP file download inside the shell script itself. Can you explain me how to perform this bath ftp from a shell script?

Answer: For downloading / uploading files using ftp in batch mode, you can either user FTP scripting using HERE document from command line, or call FTP from a shell script as explained below.

FTP Scripting using HERE document

$ ftp -in URL << SCRIPTEND
user USERNAME PASSWORD
binary
cd PATH
mget PATH
SCRIPTEND

In the above ftp scripting:

  • ftp : ftp command
  • -i : Disable interactive prompting
  • -n : Disable autologin
  • user USERNAME PASSWORD : login using the supplied user name and password
  • binary : Set binary mode for binary file transfer
  • cd PATH : change directory in remote machine
  • mget PATH : get the specified file
  • SCRIPTEND : Both the tag represents HERE document start and end.
  • HERE docs are used to provide input to commands, refer Here document to know more about it.

FTP Scripting using Shell Script

Following is a sample shell script script that downloads a tar file from the FTP server.

$ cat download.sh
ftp -in mirrors.issp.co.th << SCRIPTEND
user anonymous test@test.com
binary
cd cpan/authors/id/P/PM/PMQS/
mget Compress-Raw-Bzip2-2.027.tar.gz
SCRIPTEND

Execute this shell script to download the files from the ftp.

$ sh download.sh
$ ls
download.sh
Compress-Raw-Bzip2-2.027.tar.gz

For more FTP command refer our earlier article FTP and SFTP Beginners Guide with 10 Examples

Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • PekkaL December 14, 2010, 5:47 am
  • Chris F.A. Johnson December 14, 2010, 2:06 pm

    The ftp command is not designed for use in scripts; it is intended as an interactive command.

    While the example given may work, it is far more reliable to use the ncftp family of commands, which are designed for use in scripts, and which will give you proper error reporting.

  • Ace December 15, 2010, 10:41 am

    Agree with Chris, I have scripts that need to upload files and download them and using this mechanism did not give me reliable error reporting.

  • Madhusudhana T June 14, 2011, 7:04 am

    i want to upload the 3 zip files to switch user path in ftp binary mod how to do in shell scripting?

    rply asap…………….thanku……..