Ubuntu – List all files then execute script with part of the filename


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?

Best Answer

  • 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.