-1

I need to move old binlogs to a directory and aso compress it before moving it to a new folder.

I have a space crunch because of which we am facing issues.

below commadn is not working.

ls -t binlog* | tail -n +4 | xargs mv /path-to-directory
ls -t binlog* | tail -n +4 | xargs echo mv /path-to-directory
AReddy
  • 3,172
  • 5
  • 36
  • 76
  • Is tar an option to compress and pack logs into one tarball? – eblock Jun 18 '21 at 11:05
  • 1
    I'd suggest using logrotate instead of something you cooked up on your own - it's easy to configure. – Panki Jun 18 '21 at 11:11
  • Suggest Reading: https://unix.stackexchange.com/questions/128985/why-not-parse-ls-and-what-to-do-instead – Panki Jun 18 '21 at 11:12
  • /var/lib/mysql/binlog are important, So we dont want to delte it. we can just compress. But then still I have to move because of space crunch. – AReddy Jun 18 '21 at 11:12
  • ls | xargs mv /path-to-directory doesn't work because the file list will appear after the directory path. You could fix that with xarg's -I option. Since parsing ls output is risky anyway, however, find . -mtime XYZ -exec mv "{}" /directory + or similar might be a better solution. Or use logrotate as suggested; it can be configured to not delete or compress the original. – berndbausch Jun 18 '21 at 11:31
  • But how could i move the logs then? – AReddy Jun 18 '21 at 11:41
  • 3
    When asking for help with anything in life don't just say it's not working as that doesn't provide any information on your problem to help anyone help you solve it. Always say in what way your software/car/plumbing/lawnmower/marriage/leg/whatever "isn't working". – Ed Morton Jun 18 '21 at 14:39

1 Answers1

1

If you REALLY do not want to resort to logrotate, use find not to parse the output of ls, while printing out the last found file's modification time in seconds since 1970.01.01.

$ find ./* -maxdepth 0 -name "binlog*" -printf "%T@ %f\0" \
 | sort -z -k 1 -r \
 | cut -z -d " " -f2- \
 | tail -z -n +4 \
 | xargs -0 -I {} mv -f "{}" /path/to/directory/

The above assumes GNU coreutils, which accept -z (sort, cut and tail) or -0 (xargs) to use NUL-delimited lines, meaning the code works correctly even with newlines in the filenames.

If you can be sure there are no newlines in the file names, it turns out that you don't need to terminate each found file with a null (\0) because you are sorting line-wise on the first field (files' last modification times) which never contains problematic characters. You can simplify the above to :

$ find ./* -maxdepth 0 -name "binlog*" -printf "%T@ %f\n" \
 | sort -k 1 -r \
 | cut -d " " -f2- \
 | tail -n +4 \
 | xargs -I {} mv -f "{}" /path/to/directory/
Toby Speight
  • 8,678
Cbhihe
  • 2,701