- Empty or Delete a log files in Linux or UNIX
- How to clear the contents of a log file from the command line
- Delete a log files in Linux or UNIX using truncate
- Other commands to empty or delete a large file content in Linux
- How do I clear log file using dd on Linux or Unix?
- How to empty or truncate a file in Linux using echo/printf
- Say hello to logrotate tool
- Conclusion
- Как обрезать файлы до нулевого размера в Linux
- How to Truncate (Empty) Files in Linux
- В этом руководстве объясняется, как обрезать файлы до нулевого размера в системах Linux с помощью перенаправления оболочки и truncate команды.
- Shell Redirection
- truncate команда
- Очистить все файлы журнала
- Вывод
- Logrotate not truncating open file
- How to Empty a Log File in Linux
- 4 ways to empty a file in Linux
- Method 1: Truncate a file using truncate command
- Method 2: Empty file using :> or >
- Method 3: Using echo command to empty file in Linux
- Method 4: Use /dev/null to clear a file
Empty or Delete a log files in Linux or UNIX
How to clear the contents of a log file from the command line
Say you want to clear the contents of a log file named /var/log/messages, run:
# >/var/log/messages
The following is compatible with various Linux or Unix shells:
: > /var/log/messages
Verify file size:
# ls -l /var/log/messages
If you really wanted to delete or remove a file type the following rm command:
# rm /var/log/message
Delete a log files in Linux or UNIX using truncate
Use the truncate command to shrink or extend the size of each FILE to the specified size. So a proper way to clear log file named www.cyberciti.biz_access.log is to run the following command:
# cd /var/log/nginx/
# ls -lh www.cyberciti.biz_access.log
# truncate -s 0 www.cyberciti.biz_access.log
# ls -lh www.cyberciti.biz_access.log
Clear the contents of a file named /var/log/nginx/www.cyberciti.biz_access.log from the command line
Other commands to empty or delete a large file content in Linux
Try the cat command:
cat /dev/null > www.cyberciti.biz_access.log
Or the cp command:
# cp /dev/null /var/log/nginx/php_error.log
How do I clear log file using dd on Linux or Unix?
Type dd command as follows:
# dd if=/dev/null of=/path/to/log/file
# dd if=/dev/null of=/var/log/lighttpd/error_log
How to empty or truncate a file in Linux using echo/printf
One more method is to use the echo command:
# echo -n «» > /path/to/java/appserver.log
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Say hello to logrotate tool
A better approach is to use logrotate tool. It is designed to ease administration of systems that generate large numbers of log files. It allows automatic rotation, compression, removal, and mailing of log files. Each log file may be handled daily, weekly, monthly, or when it grows too large. See my previous logrotate help page:
Conclusion
This page showed how to empty or delete a large log file contents in Linux and Unix like systems. There are other methods too as discussed in the comments section below.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
my log files /var/log deleted is it creates any problem
/var/log is directory, if you delete the same just recreate directory using mkdir command:
mkdir /var/log
How would you specify to delete log that are over a certain age. ie 2days old or something like that. Thanks for the help.
One way is to setup new cronjob for that. Then google: “tmpwatch delete files older”
There are 2 options, either use log logrotate or use find command to get list of 2 days old files and empty them. You can find information about logrotate and about find command here only. Use search box to get information
Thank you for pointing me in the right direction. I’ve been doing some more research and had another question if you wouldn’t mine throwing in some input.
I want to remove apache logs after about a month. So I was going to set something up like this that I found online.
This is an example of a /etc/logrotate.d/httpd
/var/log/httpd/*.log <
daily
rotate 30
missingok
notifempty
sharedscripts
postrotate
/bin/kill -HUP `cat /var/run/httpd.pid 2>/dev/null` 2> /dev/null || true endscript
>
Now from what I understand this will rotate the log daily meaning create a new log everyday. The 30 means that it will hold 30 of these logs before deleting them (or compressing if I put that option in there)
Also, before I go and set this up, I want to test it on 1 websites log incase I mess things up. Would it be ok to replace the line
/var/log/httpd/*.log
with
/var/log/httpd/”website”*.log to that affect to test in one website before doing all of them?
Does it sound like I’m on the right track or am I completely lost 🙂 thanks again for your input.
simply wirte rm file.log and press enter
Use the following command:
suppose your file name is message.log then use:
This will empty the file without having deleting it.
Hallo, i have same use command as your suggest.
echo ”> message.log
but, if one folder contain much log like that, how i can clean up directly using echo command without delete it (rm)
Hi Ajeet,
Can you tell me please how it works ?
echo “” ->print the blank space
and that blank space is redirected to message.log file
or in other word your file conatins replaced by blank space without
Please could anybody help me how to delete the log files of DHCP server. and how to identify them.
Источник
Как обрезать файлы до нулевого размера в Linux
How to Truncate (Empty) Files in Linux
В этом руководстве объясняется, как обрезать файлы до нулевого размера в системах Linux с помощью перенаправления оболочки и truncate команды.
В некоторых ситуациях может потребоваться усечь (очистить) существующий файл до нулевой длины. Проще говоря, усечение файла означает удаление содержимого файла без удаления файла.
Усечение файла происходит намного быстрее и проще, чем удаление файла , его воссоздание и установка правильных прав доступа и владельца . Кроме того, если файл открывается процессом, удаление файла может привести к сбою в работе программы, которая его использует.
Shell Redirection
Самый простой и наиболее используемый метод для усечения файлов — это использование > — оператора перенаправления оболочки.
Общий формат для усечения файлов с использованием перенаправления:
- В : средстве толстой кишки true и не производит никакого вывода.
- Оператор > перенаправления перенаправляет вывод предыдущей команды в указанный файл.
- filename , файл, который вы хотите усечь.
Если файл существует , он будет обрезан до нуля. В противном случае файл будет создан.
Вместо : можно также использовать другую команду, которая не выдает никаких результатов.
Вот пример использования cat команды для вывода содержимого /dev/null устройства, которое возвращает только символ конца файла:
Еще одна команда, которая может быть использована echo . -n Опция говорит echo не для добавления новой строки:
В большинстве современных оболочек, таких как Bash или Zsh, вы можете опустить команду перед символом перенаправления и использовать:
Чтобы иметь возможность обрезать файл, вам необходимо иметь права на запись в файл. Обычно вы бы использовали sudo для этого, но привилегии суперпользователя не применяются к перенаправлению. Вот пример:
Есть несколько решений, которые позволяют перенаправлять с sudo . Первый вариант может запустить новую оболочку с помощью sudo и выполнить команду внутри этой оболочки, используя -c флаг:
Другой вариант — передать вывод в tee команду, повысить tee привилегии sudo и записать пустой вывод в заданный файл:
truncate команда
truncate утилита командной строки, которая позволяет уменьшить или расширить размер файла до заданного размера.
Общий синтаксис для усечения файлов до нулевого размера с помощью truncate команды, выглядит следующим образом:
Например, чтобы очистить журнал доступа Nginx, вы должны использовать:
Очистить все файлы журнала
Со временем ваш диск может загромождаться большим количеством больших файлов журнала, занимающих много места на диске.
Следующая команда очистит файлы, заканчивающиеся на «.log» в /var/log каталоге:
Лучшим вариантом будет вращение, сжатие и удаление файлов журналов с помощью logrotate инструмента.
Вывод
Чтобы обрезать файл в Linux, используйте оператор перенаправления, > за которым следует имя файла.
Источник
Logrotate not truncating open file
I have a system that is acting simultaneously as a test and demo platform. I’m recording a massive amount of data output by my systems that I wouldn’t be recording when this is in deployment and because of that my log files are filling up very rapidly and I eventually run out of partition space on my harddrive.
I tried logrotate , but it seems to only work if my program isn’t running. When the programs are down it properly truncates the file, records a compressed version, and discards the rest. However, when my programs that populate the log file are up and running it will properly create the compressed file, but it won’t truncate the active file. I’m trying to figure out how to make it truncate.
I’m writing to the log files with a simple redirect. ProgramA>logA , programB>logB etc. My progam is outputting every time I receive an input vector, so it’s outputting very rapidly. My assumption is that the logrotate is failing to truncate because of the constant writes to the field, but can anyone confirm rather that is the reason?
Where does logrotate keep it’s error file anyways?
Also: I want to modify the behavior of logrotate. If it activates and sees a large, say 100 MB, log file I would like it to create a copy of only the last 1 MB of the file (discarding the older 99 MB of content of the file) before truncating the original log file. I need to keep recent data, but I don’t care much about anything that is very old. Can anyone tell me how to do this?
Источник
How to Empty a Log File in Linux
You’ll find yourself in situations where you need to empty a file. This often happens when you have huge log files and How would you do that?
One not so clean way would be to remove the file and then create a new file. But this is not a good idea. It won’t be the same file, the timestamp (atime, mtime etc) will be different along with other file permissions.
Instead of creating a new empty file, you can delete its content. So, how do you empty a file in Linux? How to clear a file from all of its content without deleting the actual file?
4 ways to empty a file in Linux
There are several ways you can empty a file without actually deleting the file. Let me show you some of these methods.
Method 1: Truncate a file using truncate command
The safest way to truncate a log file is using the truncate command.
In the above command, -s is used to set/adjust the size (in bytes) of the file. When you use -s 0, it means you adjusted the file size to 0 bytes. In
Method 2: Empty file using :> or >
The simplest way to empty a file is to use the command below. If the file is not in use, it will work in Bash:
While the above works only in Bash Shell, you can use a similar command for other shells:
You can also use this command to clear a file:
Method 3: Using echo command to empty file in Linux
Another way to empty a file is via echo command in Linux:
You can also use echo command in this way:
Method 4: Use /dev/null to clear a file
You can also use the famous /dev/null and combine with the cat command to clear a log file:
In the end…
And if you don’t have enough permissions for any of the above commands, this is the sure shot but a little dirty way to achieve it:
You can also empty a file by deleting all lines in Vim editor.
If your aim was to clear log files and make some free space, you should learn about cleaning journald logs.
I hope this quick tip helped you to clear a file in Linux. Do bookmark us for more Linux quick tips.
Источник