Search code examples
bashshellrsync

Need help in for loop in shell script


I am a fresher and new to shell script. I have a file which contains file names. I want to rsync using that file names to a destination. I used for but not working. Below is the script :

basedir=/appshare/customerdata/

backupdir=/backup/

rsync=/usr/bin/rsync

ls -ltrh $basedir | awk {'print $9'} | grep .[0-9] > /tmp/include.txt

for line in /tmp/include.txt
do
    rsync -auvH $basedir$line --exclude-from /tmp/exclude.txt $backupdir
done

This script when run gives the following error :-

[root@practice Script]# ./customerdata 
sending incremental file list
rsync: change_dir "/appshare/customerdata//tmp" failed: No such file or directory (2)

sent 12 bytes  received 12 bytes  48.00 bytes/sec
total size is 0  speedup is 0.00
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1052) [sender=3.0.9]

Solution

  • Line:

    for line in /tmp/include.txt
    

    Should be:

    for line in `cat /tmp/include.txt`
    

    Also, don't parse ls output, you can use globing from shell:

    for line in $basedir/?[0-9]*;
    do
        rsync -auvH $basedir$line --exclude-from /tmp/exclude.txt $backupdir
    done