He escrito un pequeño archivo bash para hacer una copia de seguridad de un repositorio. Si el archivo de almacenamiento no existe, debe crearse. A partir de entonces, los archivos encontrados deben adjuntarse al archivo existente.
Por alguna razón, el archivo sigue siendo (re) creado / sobrescrito. Este es mi guión a continuación. ¿Alguien puede ver de dónde viene el error lógico?
#!/bin/bash
REPOSITORY_DIR=$PWD/../repository
STORAGE_DAYS=30
#https://stackoverflow.com/questions/48585148/reading-names-of-imediate-child-folders-into-an-array-and-iterating-over-it?noredirect=1#comment84167181_48585148
while IFS= read -rd '' file;
do fbname=$(basename "$file");
# Find all persisted (.CSV) files that are older than $STORAGE_DAYS
files_to_process=($(find $REPOSITORY_DIR/$fbname -type f -name '*.csv' -mtime +$STORAGE_DAYS))
backup_datafile=$REPOSITORY_DIR/$fbname/$fbname.data.tar.gz
#echo $backup_datafile
# If the tar.gz file does not exist, we want to create it
# else (i.e. file exists), we want to add files to it
# Solution from: https://stackoverflow.com/questions/28185012/how-to-create-tar-for-files-older-than-7-days-using-linux-shell-scripting
NUM_FILES_FOUND=${#files_to_process[@]}
if [ $NUM_FILES_FOUND -gt 0 ]; then
echo "Found ${#files_to_process[@]} files to process ..."
if [ ! -f backup_datafile ]; then
# Creating a new tar.gz file, since file was not found
echo "Creating new backup file: $backup_datafile"
tar cvfz $backup_datafile "${files_to_process[@]}"
else
echo "Adding files to existing backup file: $backup_datafile"
# https://unix.stackexchange.com/questions/13093/add-update-a-file-to-an-existing-tar-gz-archive
gzip -dc $backup_datafile | tar -r "${files_to_process[@]}" | gzip >$backup_datafile.new
mv $backup_datafile.new $backup_datafile
fi
# remove processed files
for filename in "${files_to_process[@]}"; do
rm -f "$filename"
done
else
echo "Skipping directory: $REPOSITORY_DIR/$fbname/. No files found"
fi
done < <(find "$REPOSITORY_DIR" -maxdepth 1 -mindepth 1 -type d -print0)
2 respuestas
Aquí es donde salió mal:
if [ ! -f backup_datafile ]; then
Supongo que debería haber sido
if [ ! -f $backup_datafile ]; then
^
O mejor aún, ponlo entre comillas:
if [ ! -f "$backup_datafile" ]; then
Si [ ! -f archivo_datos_copia de seguridad]; luego
Creo que podrías estar perdiendo una "$"
allí
Nuevas preguntas
bash
Para preguntas sobre scripts escritos para el shell de comandos Bash. Para los scripts de shell con errores / errores de sintaxis, verifíquelos con el programa shellcheck (o en el servidor web shellcheck en https://shellcheck.net) antes de publicar aquí. Es más probable que las preguntas sobre el uso interactivo de Bash sean sobre el tema en Superusuario que en Stack Overflow.