I have a bash script that iterates through a list of file locations (filepath) and deletes them. I'd like to have any errors that the command throws (like permission issues) go to an individual log as it iterates through files. Like a confirmation that the delete actually happened.
So MASTERDELETELIST.txt has a list of DeleteMeList-Category-[A-Z].txt, each one then has lines like /foo/bar/deleteme-[01-99].txt (**brackets for illustration only)
As the script iterates, it creates a report specific to that CATEGORY list. I need to push it like so: exec 2> >> $ERRORSREPORT
, which throws an error:
./script.sh: line 60: syntax error near unexpected token
>>' ./script.sh: line 60:
exec 2> >> $ERRORSREPORT'
*exact output from Terminal makes the formatting errors above)
..or exec 2> $ERRORREPORT
which doesn't seem to output anything.. when a file cannot be deleted (I chown'd it to a different user and chmod'd to 600)
How do I accomplish this?
Here's the script:
#!/bin/bash
MASTERDELETELIST="/Sandbox/masterlist.txt"
file=$MASTERDELETELIST
while IFS= read list
do # first DeleteMeList file
let "NUMBER =1"
CATEGORY="CATEGORY"
REPORT="$CATEGORY-$NUMBER-REPORT"
THISLOOPREPORT="/Sandbox/Dumpster/$REPORT-DELETEDFILES.txt"
NOTFOUNDREPORT="/Sandbox/Dumpster/$REPORT-NOTFOUND.txt"
ERRORSREPORT="/Sandbox/Dumpster/$REPORT-ERRORS.txt"
file=$list
while IFS= read line
do #run the DeleteList items
if [ -f "$line" ]
then
# found the file
echo "$line" >> $THISLOOPREPORT
rm "$line"
# exec 2> ./Sandbox/Dumpster/errors.txt this works but doesn't update with each iteration reports
# exec 2> $ERRORSREPORT ???
else
echo "file not found: $line" >> $NOTFOUNDREPORT
fi
done < $list
done < $MASTERDELETELIST
CodePudding user response:
You should redirect the stderr with exec
before you call commands that you want to be affected by this redirection, not after. In your case it would make most sense to place the exec
just before the inner while loop. Also, you for logging you probably want to use appending redirection >>
, otherwise the log file will get truncated on each iteration.
Example:
...
ERRORSREPORT="/Sandbox/Dumpster/$REPORT-ERRORS.txt"
file=$list
exec 2>> "$ERRORSREPORT"
while IFS= read line; do
...
Or as the commenter noted you can simply redirect the stderr of the inner loop, by adding the redirection after the done
part, example:
done < $list 2>> "$ERRORSREPORT"
CodePudding user response:
command >> log_file 2>> err_file