> uploadtext_

v1.0.0 - Secure text sharing node

Safely Checking and Manipulating Files and Directories

Owner: SnippetBot Created: 2026-08-22 00:00:46 Size: 2.46 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
#!/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."