I'm looking to list all files in a folder:


The file names, without the .cfg relate to a remote server name, ABC123 etc.

I want to copy a couple of files to each of the remote servers.

So, look up the filenames, but take the name without the .cfg. Then

scp filename.txt username@ABC123:/home/username/

For each remote server, overwriting the destination file if exists.

Each remote server uses the same username and password. Can I use a password in the scp command?

1 Answer 1


This should do the job:

for i in *.cfg; do
  sshpass -f /path/to/passwordfile scp ${i%.cfg}.txt username@${i%.cfg}:

or rather

for i in *.cfg;do sshpass -f /path/to/passwordfile scp ${i%.cfg}.txt username@${i%.cfg}:;done

The password is passed to scp using sshpass (following How to pass password to scp?) which reads it from passwordfile – remember to secure this file against unauthorized read access with chmod 400!

I got a little bit confused what file you want to send here, I understood there's e.g. a file ABC123.txt that has to be sent to host ABC123, so I just stripped .cfg using Bash Parameter Expansion and added .txt.

As user@host: defaults to user's home directory I removed the path.

  • AWESOME, thanks. I was closer than I thought, but couldn't get it 100%. Dec 2, 2017 at 14:42
  • Please, don't use sshpass -p. Even its manual notes that it's not very safe on most systems. Just use SSHPASS=$password sshpass -e ... instead.
    – ilkkachu
    Dec 2, 2017 at 18:54
  • @ilkkachu You're totally right, I changed the whole answer to suggest a much safer approach. Thank you!
    – dessert
    Dec 2, 2017 at 19:20
  • Though you could spare the user the trouble of making a file, and ask them for the password from the script and put in the envvar, something like read -rs pass; SSHPASS=$pass sshpass -e ... But then we're probably getting to the point where using ssh keys and ssh-agent would be smartest
    – ilkkachu
    Dec 2, 2017 at 19:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .