dhniceday

Untitled

Dec 26th, 2023
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.15 KB | None | 0 0
  1. [[ChatGPT Create Script]]
  2.  
  3. I am a programmer and need to write a bash script.
  4. The tee command is not compatible with my system.
  5. I only need the code, no explanation.
  6.  
  7. I would like to check a folder for existing files that have a timestamp in it and the prefix AF-AD.
  8.  
  9. If no file exists, do nothing.
  10.  
  11. Parse each file line by line and check if it contains the following string: "AF-AD-OK"
  12.  
  13. If not, output an error message and write "OK" in the log file.
  14.  
  15. If no error message, move the file to sub folder "done"
  16.  
  17. If it does not have the string in it, move it to an error folder and write a log entry "KO"
  18.  
  19. And the end of treatment, write "Treatment done" OK or KO in a log file.
  20.  
  21. Maintain a log file for all operations executed.
  22.  
  23. ## Answer
  24.  
  25. ```bash
  26. #!/bin/bash
  27.  
  28. # Define the directory to check and subdirectories for processed files
  29. CHECK_DIR="/path/to/check"
  30. DONE_DIR="${CHECK_DIR}/done"
  31. ERROR_DIR="${CHECK_DIR}/processed_with_error"
  32. LOG_FILE="${CHECK_DIR}/operation_log.txt"
  33.  
  34. # Create subdirectories if they don't exist
  35. mkdir -p "${DONE_DIR}" "${ERROR_DIR}"
  36.  
  37. # Function to log messages
  38. log() {
  39.     echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "${LOG_FILE}"
  40. }
  41.  
  42. # Check for files with timestamp and prefix AF-AD
  43. files=$(find "${CHECK_DIR}" -type f -name 'AF-AD-*')
  44.  
  45. # If no files found, do nothing
  46. if [ -z "$files" ]; then
  47.     exit 0
  48. fi
  49.  
  50. # Variable to keep track of overall treatment status
  51. treatment_status="OK"
  52.  
  53. # Process each file
  54. for file in $files; do
  55.     if grep -q "AF-AD-OK" "$file"; then
  56.         # If file contains "AF-AD-OK", move to "done" directory
  57.         mv "$file" "${DONE_DIR}/"
  58.         log "Processed file $(basename "$file"): OK"
  59.     else
  60.         # If file does not contain "AF-AD-OK", move to "error" directory and log KO
  61.         mv "$file" "${ERROR_DIR}/"
  62.         log "Error processing file $(basename "$file"): KO"
  63.         treatment_status="KO"
  64.     fi
  65. done
  66.  
  67. # Log final treatment status
  68. log "Treatment done: ${treatment_status}"
  69. ```
  70.  
  71. Remember to replace `/path/to/check` with the actual directory you want to monitor. Also, make sure to give execute permission to your script by running `chmod +x script.sh`.
  72.  
  73.  
Add Comment
Please, Sign In to add comment