jeudi 4 juillet 2019

If/elif statement and string comparison in shell-script

I'm trying to copy some files from a source folder to dest folders, following this:

I get the files names from des folder. If the file does exist in source folder, i copy the one from source to dest (keeping the same name).

Else, if the file from dest folder have a particular name, i'll copy a particular file from source to dest, keeping the name of dest file.

And again, if it have another particular name, i'll copy another particular file.

My problem is, for some reason, all the files which does not enter the first if statement do enter the elif statement, whatever their name is.

since the code is on a non-connected laptop, i'll just write the more important part here

SRC_FOLDER=\PATH\TO\FOLDER
DST_FOLDER=\PATH_TO\FOLDER

cd ${DST_FOLDER}
FILES=$(find . -maxdepth 1 \( -name "*.txt" -o -name "*.odp" \) -type f | sort)
for NAME in ${FILES}; do
    if [ -e ${SRC_FOLDER}/${NAME} ]; then 
        cp -fu ${SRC_FOLDER}/${NAME} ${NAME}
    elif [ ${NAME}=="SpecificName1.txt" ]; then
        cp -fu ${SRC_FOLDER}/CorrespondingFile1.txt ${NAME}
    elif [ ${NAME}=="SpecificName2.txt" ]; then
        cp -fu ${SRC_FOLDER}/CorrespondingFile2.txt ${NAME}
    fi
done

I've tried to change my elif statement by using [[ ... ]] instead of [ ... ], or $NAME instead of ${NAME} (i'd like to know the difference between those, by the way), and even =instead of ==, and a combination of all of that, but it doesn't change anything. Seems to me that any files from my FILES list which is not in SRC_FOLDER will get in the first elif statement.

I've also tried to write else if instead of elif, but the syntax doesn't seem to be accepted (script won't work at all, saying there's a problem with done)

I know there's already a lot of questions about if statement, but i couldn't find an answer to my problem in them.

Aucun commentaire:

Enregistrer un commentaire