backup.sh 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/bin/sh
  2. #
  3. # This script backs a directory up, and uploads the backup to a SSH server.
  4. #
  5. # On the server, a directory containing the date of the backup is created,
  6. # for instance 20230402 if the script was launched on the 2nd of April 2023.
  7. # The files are copied inside this directory.
  8. #
  9. # If a former directory exists, the files that are unchanged are linked to
  10. # it. So for instance, if 20230101/big_file exists and 20230102/big_file is
  11. # unchanged, then 20230102 will be a hard (not symbolic) link. This is achieved
  12. # using --link-dest from rsync (see man rsync).
  13. #
  14. # The following environment variables must be defined:
  15. # - LOCAL_FOLDER_PATH: a relative or absolute path to the directory to backup.
  16. # The script will exit with value 10 if the path does not exist, or
  17. # if the file is not a directory.
  18. # - REMOTE_FOLDER_PATH: a relative or absolute path to the directory in which
  19. # the backups are created.
  20. # - REMOTE_USER: The username to use when connecting to the SSH server.
  21. # - REMOTE_SERVER: The server to connect to.
  22. # This functions returns the last folder of the form 20230402 on the remote
  23. # SSH server, or an empty string if none is found.
  24. find_newest_folder() {
  25. ssh -o StrictHostKeyChecking=no -l "${REMOTE_USER}" "${REMOTE_SERVER}" "cd ${REMOTE_FOLDER_PATH} && ls -td ./*/ | head -1"
  26. }
  27. [[ -d "${LOCAL_FOLDER_PATH}" ]] || exit 10
  28. echo "Listing file in local folder"
  29. ls -l ${LOCAL_FOLDER_PATH}
  30. # E.g. 20230402.
  31. remote_folder=${REMOTE_FOLDER_PATH}/$(date +'%Y%m%d')
  32. echo "Looking for previous folder..."
  33. last_folder=$(find_newest_folder)
  34. if [[ -n "$last_folder" ]]; then
  35. echo "Found previous folder: ${REMOTE_FOLDER_PATH}/${last_folder}"
  36. link_parameter="--link-dest=${REMOTE_FOLDER_PATH}/${last_folder}"
  37. else
  38. echo "No previous folder found."
  39. link_parameter="--progress"
  40. fi
  41. echo "Creating remote folder: ${remote_folder}"
  42. ssh -o StrictHostKeyChecking=no -l "${REMOTE_USER}" "${REMOTE_SERVER}" "mkdir -p ${remote_folder}"
  43. cd ${LOCAL_FOLDER_PATH}
  44. echo "Copying files."
  45. rsync -e "ssh -o StrictHostKeyChecking=no" --verbose --archive "${link_parameter}" * "${REMOTE_USER}"@"${REMOTE_SERVER}":"${remote_folder}"
  46. echo "Done copying files."