Search code examples
bashloopsshellscp

shell script by read a file and copy from source and destination


I want to create shell script by reading a file like below.

/shared36/Upload/IG/01014330122022010599/
/ftpvolume/FileUpload/01014330122022010599

/shared36/Upload/IG/01010504012023003961/
/ftpvolume/FileUpload/01010504012023003961

/shared36/Upload/IG/01011005012023007397/
/ftpvolume/FileUpload/01011005012023007397

/shared36/Upload/IG/01011403012023006138/
/ftpvolume/FileUpload/01011403012023006138

/shared36/Upload/IG/01013804012023001622/
/ftpvolume/FileUpload/01013804012023001622

I want to automate below task.

scp /ftpvolume/FileUpload/01014330122022010599/ABC.PDF   /shared36/Upload/IG/01014330122022010599/ABC.PDF

scp /ftpvolume/FileUpload/01010504012023003961/ABC.PDF   /shared36/Upload/IG/01010504012023003961/ABC.PDF

and so on....

[![enter image description here][1]][1]

My script is below

#!/usr/bin/bash
dest=""
src=""
filename="test.txt"
while read -r line; do
    name="$line"
    if [[ $name =~ /shared && $name != "" ]]
    then
    echo "$name - Destination"
    fi

    if [[ $name =~ /ftpvolume && $name != "" ]]
    then
    echo "$name - Source"
    fi
    sleep 1
done< "$filename"

but I just want to put its source and destination into scp command


Solution

  • Set variables after each match. Then after you read the source, substitute them into the scp command.

    #!/usr/bin/bash
    dest=""
    src=""
    filename="test.txt"
    while read -r line; do
        name="$line"
        if [[ $name =~ /shared ]]
        then
            dest=$name
        elif [[ $name =~ /ftpvolume ]]
        then
            src=$name
            scp "$src/ABC.PDF" "$dest/ABC.PDF"
        fi
        sleep 1
    done< "$filename"