I was facing a similar situation where I had to delete Docker Container Logs with ".log" extension using a command or a shell script (it was scenario-specific)
Here's the script
#!/bin/bash
#SHELL SCRIPT TO DELETE THE CONTENT OF THE DOCKER CONTAINER LOG FILES
#Declaring Array
file_list=()
#While loop to read log file name
while IFS= read -d $'\0' -r file ; do
file_list=("${file_list[@]}" "$file")
done < <(find /var/lib/docker/containers/ -type f -name "*.log" -print0)
#Printing log file names
echo "${file_list[@]}"
#Deleting the content of the log files
for f in "${file_list[@]}";do
if [ -f $f ]
then
: > "$f"
fi
done
Explanation of Bash Elements
file_list=()
is an array containing the results of find /var/lib/docker/containers/ -type f -name "*.log"
While loop is used to read the log file names
while IFS= read -d $'\0' -r file ; do
file_list=("${file_list[@]}" "$file")
done < <(find /var/lib/docker/containers/ -type f -name "*.log" -print0)
where the find
subprocess is used by the while
command via <
and IFS= read -d $'\0' -r file
is the while condition
which reads one line of input from the find
command.
echo "${file_list[@]}"
is to print the file name stored in the array.
for f in "${file_list[@]}";do
if [ -f $f ]
then
: > "$f"
fi
done
In the above for-(if)-loop snippet, the loop reads each file from the array ${file_list[@]}
and the if
statement then
clears the content of the file using : > "$f"