How to treat avariety in bash?

2

I'm having a problem, I'm doing a bash script to run using crontab, which syncs my ssd files with the hd and dropbox.

Script:

#!/bin/bash -

PC_DIR="~/Programming"
DROP_DIR="~/Dropbox/Programação"

PC_FILES="$(find ${PC_DIR} -follow)"
DROP_FILES="$(find ${DROP_DIR} -follow)"

for FILE1 in "${PC_FILES}"
do
    echo "FILE1=${FILE1}"
    for FILES2 in "${DROP_FILES}"
    do
        echo "FILE2=${FILE2}"
        if [ "${FILE1}" -nt "${FILE2}" ];
        then
            cp "${FILE1}" "${FILE2}"

        elif [ "${FILE1}" -ot ""${FILE2} ];
        then
            cp "${FILE2}" "${FILE1}"
        fi
    done
done

The problem with the script is that it treats the "FILEx" variables as a large block of text with several line break functions ('\ n') eg:

FILE1=~/Programming
~/Programming/C++
~/Programming/C++/teste.cpp
~/Programming/C++/test.cpp

In order to do the 'NewerThan' and 'OlderThan' tests, I need to be able to look at each line as a different directory, not as a big block,     

asked by anonymous 20.12.2017 / 04:40

1 answer

1

The error is in "$ {PC_FILES}" and "{DROP_FILES}" . With the quotation marks, he is basically telling the algorithm to capture everything as a string and play the variable FILE1 and FILE2 respectively.

The solution to your code is to do this:

#!/bin/bash

PC_DIR="after"
DROP_DIR="bkp"

PC_FILES="$(find ${PC_DIR} -follow)"
DROP_FILES="$(find ${DROP_DIR} -follow)"

IFS=$'\n'

for FILE1 in ${PC_FILES}
do
    echo "FILE1=${FILE1}"
    for FILE2 in ${DROP_FILES}
    do
        echo "FILE2=${FILE2}"
        if [ "${FILE1}" -nt "${FILE2}" ];
        then
           echo "Copia ${FILE1} para ${FILE2}"

        elif [ "${FILE1}" -ot ""${FILE2} ];
        then
            echo "Copia ${FILE2} para ${FILE1}"
        fi
    done
done

There is another way, too, to read the output from find (or any other command) that is using the read together with the while

#!/bin/bash -

PC_DIR="after"
DROP_DIR="bkp"

PC_FILES="$(find ${PC_DIR} -follow)"
DROP_FILES="$(find ${DROP_DIR} -follow)"

IFS="\"

while read FILE1; do

        while read FILE2; do

                if [ "${FILE1}" -nt "${FILE2}" ]; then
                    echo -e "Copia ${FILE1} para ${FILE2}\n"

                elif [ "${FILE1}" -ot ""${FILE2} ]; then
                    echo -e "Copia ${FILE2} para ${FILE1}\n"
                fi

        done <<< ${DROP_FILES}

done <<< ${PC_FILES}

I often prefer while ¹

  

Please note that you add one more line, IFS . This variable is nothing more than a "separator".   It basically informs bash how to recognize the fields, boundaries, etc.

¹ To know the difference between while / for, I recommend reading Reading lines from a file with bash: for vs. while

    
20.12.2017 / 06:17