Search code examples
linuxbashrsyncsmb

Linux script for copying files from multiple windows machines


Having a issue trying to make a bash script that will read ip address and usernames from a file that mount a connection to that share on windows and then copy ano file types into a new folder called the users name. At the moment it doesn't quite work, it makes hundreds of folders called *.ano if it can not find the windows share.

Help please

Text file:

192.168.0.2 user1
192.168.0.3 user2

bash script:

USER='/home/user/user.ip'
IPADDY=$(grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' $USER)
USERNAME=$(awk '{ print $NF }' $USER)
for i in $IPADDY $USERNAME
do
    mkdir /home/user/Documents/$USERNAME
    mount -t smbfs //$IPADDY/$USERNAME /home/user/$USERNAME
    rsync -va /home/user/$USERNAME/*.ano /home/user/Documents/$USERNAME/*.ano
done

Hi all thanks for such a quick reply, I have change the code as follow but still get multiple files have I done something wrong here

    USER='/home/user/user.ip'
IPADDY=$(grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' $USER)
USERNAME=$(awk '{ print $NF }' $USER)
while read IPADDY USERNAME; do
mkdir /home/user/Documents/$USERNAME
mount -t smbfs //$IPADDY/$USERNAME /home/user/$USERNAME
rsync -va /home/user/$USERNAME/*.ano /home/user/Documents/$USERNAME/
done < $USER

Solution

  • The problem is in the for command. In your script, i iterates over the contents of $IPADDY, then it iterates over the contents of $USERNAME. Meanwhile, $USERNAME inside the loop gets expanded to user1 user2, resulting in:

    mkdir /home/user/Documents/user1 user2
    

    The mount line becomes:

    mount -t smbfs //192.168.0.2 192.168.0.3/user1 user2 /home/user/user1 user2
    

    And so on.

    Rather, loop over the file itself:

    while read IPADDY USERNAME; do
      #awesome things here based on $IPADDY and $USERNAME
    done < $USER
    

    You might want to add [[ -z $IPADDY ]] && continue to skip over any possible blank lines in the file.