- Как обрезать (пустые) файлы в Linux
- Перенаправление оболочки
- команда truncate
- Очистить все файлы журнала
- Выводы
- 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
- 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
- How to clean log file? [duplicate]
- 1 Answer 1
Как обрезать (пустые) файлы в Linux
В некоторых ситуациях вам может потребоваться обрезать (очистить) существующий файл до нулевой длины. Проще говоря, усечение файла означает удаление содержимого файла без удаления файла.
Усечение файла намного быстрее и проще, чем удаление файла , его воссоздание и установка правильных разрешений и прав собственности . Кроме того, если файл открывается каким-либо процессом, его удаление может вызвать сбой в работе программы, которая его использует.
В этом руководстве объясняется, как обрезать файлы до нулевого размера в системах Linux с помощью перенаправления оболочки и команды truncate .
Перенаправление оболочки
Самый простой и наиболее часто используемый метод обрезки файлов — использование оператора перенаправления оболочки > .
Общий формат усечения файлов с использованием перенаправления:
- : Двоеточие означает true и не выводит ничего.
- Оператор перенаправления > перенаправляет вывод предыдущей команды в данный файл.
- filename , файл, который вы хотите обрезать.
Если файл существует , он будет обрезан до нуля. В противном случае файл будет создан.
Вместо : можно также использовать другую команду, которая не выводит никаких результатов.
Вот пример использования команды cat для вывода содержимого устройства /dev/null , которое возвращает только символ конца файла:
Еще одна команда, которую можно использовать, — это echo . Параметр -n указывает echo не добавлять новую строку:
В большинстве современных оболочек, таких как Bash или Zsh, вы можете опустить команду перед символом перенаправления и использовать:
Чтобы иметь возможность обрезать файл, вам необходимо иметь права на запись в файл. Обычно для этого используется sudo , но повышенные привилегии root не применяются к перенаправлению. Вот пример:
Есть несколько решений, позволяющих перенаправлять с помощью sudo . Первый вариант может запустить новую оболочку с помощью sudo и выполнить команду внутри этой оболочки, используя флаг -c :
Другой вариант — передать вывод команде tee , повысить привилегии tee с помощью sudo и записать пустой вывод в заданный файл:
команда truncate
truncate — это служебная программа командной строки, позволяющая уменьшить или увеличить размер файла до заданного размера.
Общий синтаксис усечения файлов до нулевого размера с помощью команды truncate выглядит следующим образом:
Параметр -s 0 устанавливает нулевой размер файла.
Например, чтобы очистить журнал доступа к Nginx, вы должны использовать:
Очистить все файлы журнала
Со временем на вашем диске может появиться множество больших файлов журнала, занимающих много места на диске.
Следующая команда очистит файлы, заканчивающиеся на «.log» в каталоге /var/log :
Лучшим вариантом было бы повернуть, сжать и удалить файлы журналов с помощью инструмента logrotate .
Выводы
Чтобы обрезать файл в Linux, используйте оператор перенаправления > за которым следует имя файла.
Если у вас есть вопросы или замечания, пожалуйста, оставьте комментарий ниже.
Источник
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.
Источник
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.
Источник
How to clean log file? [duplicate]
Is there a better way to clean the log file? I usually delete the old logfile and create a new logfile and I am looking for a shorter type/bash/command program. How can I use an alias?
1 Answer 1
(fell free to substitute false or any other command that produces no output, like e.g. : does in bash ) if you want to be more eloquent, will all empty logfile (actually they will truncate it to zero size).
If you want to know how long it «takes», you may use
(which is the same as dd if=/dev/null > logfile , by the way)
You can also use
(or truncate -s 0 logfile ) to be perfectly explicit or, if you don’t want to,
(in which case you are relying on the common behaviour that applications usually do recreate a logfile if it doesn’t exist already).
However, since logfiles are usually useful, you might want to compress and save a copy. While you could do that with your own script, it is a good idea to at least try using an existing working solution, in this case logrotate , which can do exactly that and is reasonably configurable.
Should you need to do it for several files, the safe way is
Some shells ( zsh ) also allow one to specify several redirection targets.
This works (at least in bash ) since it creates all the redirections required although only the last one will catch any input (or none in this case). The tee example with several files should work in any case (given your tee does know how to handle several output files)
Of course, the good old shell loop would work as well:
although it will be much slower due to the command being run separately for each file. That may be helped by using find :
Источник