How to specify FTP credentials in command line scripts

It’s easy to establish an FTP connection using the ftp command from the Linux Command Line. Sadly this command does not accept login credentials as parameters – which means that if we use it in a script, our script will pause and wait for us to type those credentials in manually. Not really suitable for automated backups.

Thanks to a clever mechanism called netrc we can create a file in the home directory of the user who runs the script and provide credentials there. Let me show you how this works.

First we create a file called .netrc. It’s a hidden file and it needs to reside in the home directory of the user who will connect via FTP. I’m going to use root for this:

The first line is just a comment to you can remember how to add parameters here. The second line is an example of a host you want to connect to. Add as many other servers as you like, all following the same pattern.

Be aware that you need to connect to the server as it is specified in the .netrc file. In the above example, if you would connect to domain.com instead, you would be asked for credentials as netrc cannot find a match.

The .netrc file needs to be readable only by this one user, otherwise connections may fail. We do this by changing the file permissions to 600:

That should do it! Try to connect with

and the connection will be established without the prompt for credentials.

If netrc isn’t working for you, or you choose not to use it, note that you can also provide FTP credentials with a here script. I find that approach a bit clunky, but the following link has details on how to do that:

About Jay Versluis

Jay is a medical miracle known as a Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Add your voice!