Delete Except Newest Files Bash

The provided Bash commands are useful for listing and deleting files, including dotfiles, except for the newest ones. Here’s a breakdown of what each command does:

List all files except the newest three:

1
ls -t | tail -n +4
  • ls -t: Lists all files in the current directory sorted by modification time in descending order (newest first).
  • tail -n +4: Displays all lines starting from the fourth line. In this context, it shows all files except the newest three.

Delete those files:

1
ls -t | tail -n +4 | xargs rm --
  • xargs: Takes the output from the previous command (the list of files to delete) and passes them as arguments to the rm (remove) command.
  • rm --: Deletes the specified files.

List all dotfiles except the newest three:

1
ls -At | tail -n +4
  • ls -At: Lists all files, including dotfiles, sorted by modification time in descending order.
  • tail -n +4: Displays all lines starting from the fourth line. It shows all dotfiles except the newest three.

Delete dotfiles:

1
ls -At | tail -n +4 | xargs rm --
  • xargs: Takes the output from the previous command (the list of dotfiles to delete) and passes them as arguments to the rm (remove) command.
  • rm --: Deletes the specified dotfiles.

It’s important to use these commands with caution, especially the ones that involve deletion (xargs rm --). Deleting files is irreversible, and there’s no easy way to recover them if you make a mistake. Make sure you’re in the correct directory and that you are certain about the files you want to delete before running these commands.

Additionally, always have backups of important data before performing mass file deletions to avoid accidental data loss.

0%