Linux Tutorials - Herong's Tutorial Examples - v5.45, by Herong Yang
Truncate Log Files
This section provides a tutorial example on how to truncate log files in Linux computers.
If you are running some server programs on your Linux computer, you may see some large log files on the hard disk. For example, the following command shows a log file with 74 MB of an old Apache Web server:
herong$ ls -l /var/log/apache2/error_log -rw-r--r-- 1 root wheel 74947393 Nov 6 10:37 /var/log/apache2/error_log
To save disk space, you should save a backup copy in an offline storage and truncate the log file to zero byte.
Here are some general guidelines on truncating log files.
1. Do not truncate the log file, if it is already rotated by the server program. For example: the following command shows rotated log files of an Apache Web server.
herong$ sudo ls -l /var/log/httpd/ -rw-r--r--. 1 root root 441 Oct 31 03:27 error_log -rw-r--r--. 1 root root 7576 Oct 10 03:25 error_log-20211010 -rw-r--r--. 1 root root 1505 Oct 17 03:26 error_log-20211017 -rw-r--r--. 1 root root 5760 Oct 24 03:10 error_log-20211024 -rw-r--r--. 1 root root 6576 Oct 31 03:27 error_log-20211031
2. Do not delete the log file using the "rm" command. Some server program will crash, if its log file is gone. Also re-creating an empty log file with the original permissions takes multiple commands.
3. Redirect empty output to the log file. Here are some example commands:
herong$ : > /var/log/apache2/error_log herong$ echo -n /var/log/apache2/error_log herong$ cat /dev/null > /var/log/apache2/error_log
4. Add "sudo" command, if you don't have "write" permission on the log file. Here are some example commands:
herong$ sudo sh -c ': > /var/log/apache2/error_log' herong$ sudo sh -c 'echo -n /var/log/apache2/error_log' herong$ sudo sh -c 'cat /dev/null > /var/log/apache2/error_log' herong$ cat /dev/null | sudo tee /var/log/apache2/error_log
5. Use "truncate" command as shown below:
herong$ truncate -s 0 /var/log/apache2/access.log herong$ sudo truncate -s 0 /var/log/apache2/access.log
Table of Contents
Cockpit - Web Portal for Administrator
"more", "head" and "cat" - Read Files
"split" and "cat" - Split and Join Files
"compress/uncompress" - Compressed *.Z Files
"gzip/gunzip" - Compressed *.gz Files
"xz/unxz" - Compressed *.xz or *.lzma Files
"tar -c" and "tar -x" - Create and Extract Archive Files
"zip" and "unzip" - Create and Extract ZIP Files
"Operation not permitted" Error on macOS
SELinux - Security-Enhanced Linux
SSH Protocol and ssh/scp Commands
Software Package Manager on CentOS - DNF and YUM
vsftpd - Very Secure FTP Daemon