I want to empty (not delete) log files daily at a particular time. something like
echo "" > /home/user/dir/log/*.log
but it returns
-bash: /home/user/dir/log/*.log: ambiguous redirect
is there any way to achieve this?
CodePudding user response:
You can try this.
Remove and recreate those files using For Loop.
create .sh file ( something.sh ) and add below code in it.
#!/bin/bash
for f in /home/user/dir/log/*.log
do
[ -f "$f" ] && rm "$f"
touch "$f"
done
run in cron every night
* 22 * * * /file path/something.sh
CodePudding user response:
You can't redirect to more than one file, but you can tee
to multiple files.
tee /home/user/dir/log/*.log </dev/null
The redirect from /dev/null
also avoids writing an empty line to the beginning of each file, which was another bug in your attempt. (Perhaps specify nullglob
to avoid creating a file with the name *.log
if the wildcard doesn't match any existing files, though.)
However, a much better solution is probably to use the utility logrotate
which is installed out of the box on every Debian (and thus also Ubuntu, Mint, etc) installation. It runs nightly by default, and can be configured by dropping a file in its configuration directory. It lets you compress the previous version of a log file instead of just overwrite, and takes care to preserve ownership and permissions etc.