matthieuheitz
2/20/2017 - 4:26 PM

Bash - Avoid overwriting a folder and its content by creating indexed folders

Bash - Avoid overwriting a folder and its content by creating indexed folders

# Avoid overwriting on output folder
if [ ! -d "$OUT_FOLDER_PATH" ]; then # If folder doesn't exist, create it
    mkdir $OUT_FOLDER_PATH
else
    cpt=0
    OUT_FOLDER_PATH_NEW=$OUT_FOLDER_PATH
    while [ "$(ls -A $OUT_FOLDER_PATH_NEW 2> /dev/null)" ] ; # while folder exist and is not empty
    do
        let cpt=cpt+1
        echo $cpt
        OUT_FOLDER_PATH_NEW=${OUT_FOLDER_PATH}-$cpt
    done
    OUT_FOLDER_PATH=$OUT_FOLDER_PATH_NEW
    if [ ! -d "$OUT_FOLDER_PATH_NEW" ]; then
        mkdir $OUT_FOLDER_PATH
    fi
fi