#!/bin/bash # --- Configuration --- FILE_PATH="/tmp/my_temp_file.txt" DIR_PATH="/tmp/my_temp_dir" BACKUP_DIR="/tmp/backups" LOG_FILE="/var/log/file_manipulator.log" set -e set -u set -o pipefail log() { local type="$1" local message="$2" echo "$(date '+%Y-%m-%d %H:%M:%S') [FILE_MANIP] [${type}] ${message}" | tee -a "${LOG_FILE}" } error_exit() { log "ERROR" "Script failed at line ${BASH_LINENO[0]} while executing: '${BASH_COMMAND}'" exit 1 } trap 'error_exit' ERR # --- Main Logic --- log "INFO" "Starting file and directory manipulation checks." # 1. Check if a file exists (and is a regular file) if [ -f "${FILE_PATH}" ]; then log "INFO" "File '${FILE_PATH}' exists. Content:" cat "${FILE_PATH}" else log "INFO" "File '${FILE_PATH}' does not exist. Creating it..." echo "This is a test file created by the script." > "${FILE_PATH}" log "INFO" "File '${FILE_PATH}' created." fi # 2. Check if a directory exists if [ -d "${DIR_PATH}" ]; then log "INFO" "Directory '${DIR_PATH}' exists." else log "INFO" "Directory '${DIR_PATH}' does not exist. Creating it..." mkdir -p "${DIR_PATH}" # -p creates parent directories if they don't exist log "INFO" "Directory '${DIR_PATH}' created." fi # 3. Check if *any* entry exists (file, directory, link, etc.) if [ -e "${FILE_PATH}" ]; then log "INFO" "Entry '${FILE_PATH}' exists (could be file, dir, link)." else log "WARN" "Entry '${FILE_PATH}' somehow disappeared after creation check!" fi # 4. Moving files with checks if [ -f "${FILE_PATH}" ]; then log "INFO" "Moving '${FILE_PATH}' to '${DIR_PATH}/$(basename ${FILE_PATH})' ..." mv "${FILE_PATH}" "${DIR_PATH}/$(basename ${FILE_PATH})" log "INFO" "File moved." else log "WARN" "Cannot move, '${FILE_PATH}' does not exist." fi # 5. Creating a backup directory and copying if [ ! -d "${BACKUP_DIR}" ]; then log "INFO" "Creating backup directory: ${BACKUP_DIR}" mkdir -p "${BACKUP_DIR}" fi log "INFO" "Copying content of '${DIR_PATH}' to '${BACKUP_DIR}' ..." cp -r "${DIR_PATH}" "${BACKUP_DIR}/$(basename ${DIR_PATH})_$(date +%Y%m%d%H%M%S)" log "INFO" "Content copied to backup." # 6. Cleaning up (removing a directory and its contents) if [ -d "${DIR_PATH}" ]; then log "WARN" "Removing directory '${DIR_PATH}' and its contents recursively..." rm -rf "${DIR_PATH}" log "INFO" "Directory '${DIR_PATH}' removed." else log "INFO" "Directory '${DIR_PATH}' already removed or never existed." fi log "INFO" "File and directory manipulation checks finished."