1

I am trying to fetch a directory from multiple Linux hosts to a localhost via a bash script. But the hostname command shows the output of localhost instead of the remote host. The directory structure is : /home/user/HOSTNAME-BCKP on all the servers.

#!/bin/bash
for i in $(cat hosts);
do
scp -r $i:/home/user/`hostname`-BCKP/home/user/ALL-BCKPs/;
done

1 Answer 1

0

If you want the hostname-command to show the remote hostname, you need to run it on the remote host.

You could read them into an associative array and loop over that:

#!/bin/bash -

declare -A myhosts
for item in $(cat hosts); do
  myhosts[$item]="$(ssh $item 'hostname')"
done

for key in "{!myhosts[@]}" ; do
  scp -r $key:/home/user/${myhosts[$key]}-BCKP /home/user/ALL-BCKPs/
done

But if you want to do this more than once, consider creating a file with a pair of host and hostname per line.

You can read that in a while-loop:

while read -r myhost myhostname; do
  # do something with $myhost and $myhostname
done < yourfile

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.