Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [[ChatGPT Create Script]]
- I am a programmer and need to write a bash script.
- The tee command is not compatible with my system.
- I only need the code, no explanation.
- I would like to check a folder for existing files that have a timestamp in it and the prefix AF-AD.
- If no file exists, do nothing.
- Parse each file line by line and check if it contains the following string: "AF-AD-OK"
- If not, output an error message and write "OK" in the log file.
- If no error message, move the file to sub folder "done"
- If it does not have the string in it, move it to an error folder and write a log entry "KO"
- And the end of treatment, write "Treatment done" OK or KO in a log file.
- Maintain a log file for all operations executed.
- ## Answer
- ```bash
- #!/bin/bash
- # Define the directory to check and subdirectories for processed files
- CHECK_DIR="/path/to/check"
- DONE_DIR="${CHECK_DIR}/done"
- ERROR_DIR="${CHECK_DIR}/processed_with_error"
- LOG_FILE="${CHECK_DIR}/operation_log.txt"
- # Create subdirectories if they don't exist
- mkdir -p "${DONE_DIR}" "${ERROR_DIR}"
- # Function to log messages
- log() {
- echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "${LOG_FILE}"
- }
- # Check for files with timestamp and prefix AF-AD
- files=$(find "${CHECK_DIR}" -type f -name 'AF-AD-*')
- # If no files found, do nothing
- if [ -z "$files" ]; then
- exit 0
- fi
- # Variable to keep track of overall treatment status
- treatment_status="OK"
- # Process each file
- for file in $files; do
- if grep -q "AF-AD-OK" "$file"; then
- # If file contains "AF-AD-OK", move to "done" directory
- mv "$file" "${DONE_DIR}/"
- log "Processed file $(basename "$file"): OK"
- else
- # If file does not contain "AF-AD-OK", move to "error" directory and log KO
- mv "$file" "${ERROR_DIR}/"
- log "Error processing file $(basename "$file"): KO"
- treatment_status="KO"
- fi
- done
- # Log final treatment status
- log "Treatment done: ${treatment_status}"
- ```
- 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`.
Add Comment
Please, Sign In to add comment