Paprastas backup skriptas Linux
Paprastas ir galingas failų atsarginių kopijų įrankis „b“ terminalui (Perl)#
Dar 2014 metais susidūriau su kasdiene problema – dirbant su sisteminiais failais (.zshrc, .conf, įvairiais skriptais) terminale, prieš darant pakeitimus visada norisi turėti atsarginę kopiją. Žinoma, galima naudoti standartinę komandą cp failas failas.bak, bet kai kopijų atsiranda daugiau, prasideda chaosas. Sunku atsekti, kada kuri kopija daryta, o norint atkurti failą ar pažiūrėti skirtumus, tenka kopijuoti ir vesti ilgus failų pavadinimus.
Taip ir gimė šis Perl skriptas, trumpai pavadintas tiesiog „b“ (nuo žodžio backup). Praėjus daugeliui metų, nusprendžiau šį projektą prikelti, optimizuoti ir pritaikyti šiuolaikiniams poreikiams: atsisakiau visų išorinių CPAN modulių, pridėjau 256 spalvų palaikymą ir galimybę operuoti failais tiesiog nurodant jų ID numerį.

Kam šis skriptas reikalingas?#
Skriptas skirtas programuotojams, sistemų administratoriams ir GNU/Linux entuziastams, norintiems maksimaliai pagreitinti darbą terminale. Pagrindiniai privalumai:
- Greitis ir patogumas: Užuot rašę ilgą kelią, tiesiog rašote
b .zshrcir atsarginė kopija sukurta. - Tvarka: Visų kopijų istorija sekama vietinėje duomenų bazėje (
~/.brc). Paleidus komandąb, matote gražų, tvarkingą sąrašą. - Spalvinis kodavimas (ANSI 256): Terminale duomenys pateikiami vizualiai patraukliai. Failo amžius nuspalvintas priklausomai nuo to, ar kopija daryta prieš kelias sekundes (raudona), minutes (rožinė), valandas (geltona) ar dienas (pilka).
- Nereikia rašyti ilgų kelių: Norint palyginti originalą su kopija, atkurti ar ištrinti, užtenka nurodyti indekso ID iš sąrašo (pvz.,
b diff 2). - Jokių priklausomybių (Zero Dependencies): Skriptas naudoja tik bazinius, į pačią „Perl“ kalbą įmontuotus modulius. Jums nereikia siųstis jokių paketų per
cpan– skriptas veiks bet kokiame serveryje iškart. - Savaiminis išsivalymas: Jei atsarginę kopiją ištrinsite rankiniu būdu (su standartine
rmkomanda), skriptas pats supras, kad failo nebėra, ir automatiškai išvalys jo įrašą iš duomenų bazės.
Pagrindinės komandos#
b <failo_pavadinimas>– sukuria atsarginę failo kopiją (pvz., pridedant priesagą.20261029_173659).b(arbab list) – parodo visų sukurtų kopijų lentelę su indeksais (ID), originalia data, failo senumu, dydžiu ir keliu.b diff <ID>– spalvotai (diff -uformatu) palygina originalų failą su nurodyta atsargine kopija. Pridėtos eilutės rodomos žaliai, ištrintos – raudonai.b restore <ID>– atkuria originalų failą iš atsarginės kopijos.b rm <ID>– saugiai ištrina atsarginę kopiją ir pašalina ją iš istorijos.b help– parodo pagalbos meniu.
Diegimas ir Kodas#
Išsaugokite šį kodą faile pavadinimu b, suteikite jam vykdymo teises (chmod +x b) ir įkelkite į savo $PATH (pvz., ~/.local/bin/ ar ~/bin/). Norėdami paskaityti dokumentaciją, terminale tiesiog įveskite perldoc b.
#!/usr/bin/perl
# ==============================================================================
# Script: b (Backup Utility)
# Created: 15 Jan 2014 by Mindaugas Nefas
# Updated: 2026
# Description: A zero-dependency, colorful CLI tool for quick file backups.
# Features: Index/ID support, Diffing, Restoring, Purging, 256 ANSI colors.
# ==============================================================================
use strict;
use warnings;
use Cwd qw(abs_path);
use POSIX qw(strftime);
# --- Color Palette (256 ANSI Colors) ---
# Used for terminal output formatting.
my $C_RST = "\e[0m";
my $C_GRN = "\e[38;5;114m"; # Soft Green (Success, Sizes)
my $C_CYN = "\e[38;5;73m"; # Cyan (Dates, Diff context)
my $C_ORG = "\e[38;5;215m"; # Orange (Headers, File names)
my $C_GRY = "\e[38;5;243m"; # Gray (Indexes, Borders, Days)
my $C_RED = "\e[38;5;160m"; # Red (Errors, Seconds)
my $C_PNK = "\e[38;5;162m"; # Pink (Minutes)
my $C_YLW = "\e[38;5;220m"; # Yellow (Hours)
my $C_BLU = "\e[38;5;39m"; # Bright Blue (Backup paths)
my $C_ADD = "\e[38;5;40m"; # Green (Diff additions)
my $C_DEL = "\e[38;5;196m"; # Red (Diff deletions)
# Database file to store backup history
my $backups = "$ENV{HOME}/.brc";
# Ensure the database file exists before proceeding
if (! -e $backups) {
open(my $fh, '>>',$backups) or die "${C_RED}Could not create$backups: $!${C_RST}\n";
close($fh);
}
# --- Command Routing ---
# Parse the first argument to determine the action. Defaults to 'list'.
my $cmd =$ARGV[0] || 'list';
if ($cmd eq 'help' || $cmd eq '-h' \vert{}\vert{}$cmd eq '--help') {
do_help();
} elsif ($cmd eq 'diff' && defined$ARGV[1]) {
do_diff($ARGV[1]);
} elsif ($cmd eq 'restore' && defined$ARGV[1]) {
do_restore($ARGV[1]);
} elsif ($cmd eq 'rm' && defined$ARGV[1]) {
do_rm($ARGV[1]); } elsif (-e$cmd) {
# If the argument is an existing file, create a backup
do_backup($cmd);
} elsif ($cmd eq 'list') {
do_list();
} else {
warn "${C_RED}Unknown command or file not found: $cmd${C_RST}\n";
do_help();
}
# ==============================================================================
# Core Functions
# ==============================================================================
# Prints the usage instructions.
sub do_help {
print "${C_ORG}Usage:${C_RST}\n";
print " b <file> ${C_GRY}- Create a backup of the specified file${C_RST}\n";
print " b ${C_GRY}- List all backups${C_RST}\n";
print " b diff <ID|file> ${C_GRY}- Compare backup with the original file${C_RST}\n";
print " b restore <ID|file> ${C_GRY}- Overwrite original file with the backup${C_RST}\n";
print " b rm <ID|file> ${C_GRY}- Delete a backup file${C_RST}\n";
print " b help ${C_GRY}- Show this help menu${C_RST}\n";
}
# Creates a backup of the given file with a timestamp suffix.
sub do_backup {
my $raw_path = shift;
my $file = abs_path($raw_path);
if ($file && -f$file) {
# Generate timestamps for DB and file suffix
my $time = strftime "%Y-%m-%d %H:%M:%S", localtime;
my $suffix = strftime "%Y%m%d_%H%M%S", localtime;
my $back_file = "$file.$suffix";
# Prevent overwriting if multiple backups are made in the same second
my $counter = 1;
while (-e $back_file) {
$back_file = "$file.$suffix.$counter";
$counter++;
}
# Perform the actual file copy
if (!copy_file($file,$back_file)) {
die "${C_RED}Failed to copy $file to$back_file: $!${C_RST}\n";
}
# Append the new backup record to the DB
open(my $fh, '>>',$backups) or die "${C_RED}Cannot open$backups: $!${C_RST}\n";
print $fh "$time$back_file\n";
close($fh);
print "${C_GRN}Backup created:${C_RST}${C_BLU}$back_file${C_RST}\n";
} else {
warn "${C_RED}I can't read that file: $raw_path${C_RST}\n";
exit(1);
}
}
# Lists all backups, formats them into a neat table, and auto-purges missing files.
sub do_list {
open(my $fh, '<',$backups) or die "${C_RED}Cannot read$backups: $!${C_RST}\n";
my @items = <$fh>;
close($fh);
my $count = 0;
my @valid_lines;
my $db_needs_update = 0;
foreach my $line (@items) {
# Strict regex to parse the DB line (YYYY-MM-DD HH:MM:SS /path/to/file)
if ($line =~ m/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) (.+)$/s) {
my ($date, $time,$file) = ($1, $2, $3);
chomp($file);
# Check if the backup file still exists on the disk
if (-s $file) {$count++;
push @valid_lines, $line;
# Fetch file metadata for formatting
my @st = stat($file);
my $age_str = format_age_colored($st[9]);
my $size_str = format_bytes($st[7]);
my $datetime_str = "${C_CYN}${date} ${time}${C_RST}";
# Print formatted row (using pad_ansi to ignore invisible color codes)
printf("%s%2d%s | %s | %s | %s | %s%s%s\n",
$C_GRY,$count, $C_RST,$datetime_str,
pad_ansi($age_str, 6, 1),
pad_ansi($size_str, 6, 1),$C_BLU, $file,$C_RST
);
} else {
# File is missing, mark DB for rewrite to clean up dead entries
$db_needs_update = 1;
}
}
}
# Rewrite the DB file if we found missing entries
if ($db_needs_update) {
open(my $out_fh, '>',$backups) or die "${C_RED}Cannot update$backups: $!${C_RST}\n";
print $out_fh @valid_lines;
close($out_fh);
}
print "\n${C_GRY}The system is clean.${C_RST}\n" if $count == 0;
}
# Compares a backup against its original file using the system's `diff` utility.
sub do_diff {
my $backup_file = resolve_target(shift);
if (!$backup_file \vert{}\vert{} !-e$backup_file) {
die "${C_RED}Backup file not found or invalid ID.${C_RST}\n";
}
# Extract the original file path by stripping the timestamp suffix
my $orig_file =$backup_file;
$orig_file =~ s/\.\d{8}_\d{6}(?:\.\d+)?$//;
if (!-e $orig_file) {
print "${C_RED}Original file ($orig_file) no longer exists!${C_RST}\n";
print "${C_GRY}You can restore it using: b restore $backup_file${C_RST}\n";
return;
}
print "${C_CYN}Comparing: ${C_ORG}$orig_file ${C_CYN}vs${C_ORG}$backup_file${C_RST}\n";
# Pipe output from diff and apply colors line by line
open(my $diff_fh, '-|', "diff -u '$backup_file' '$orig_file'") or die "${C_RED}Diff command failed: $!${C_RST}\n";
while (<$diff_fh>) {
if (/^\+/) { print "${C_ADD}$_"; }
elsif (/^\-/) { print "${C_DEL}$_"; }
elsif (/^@@/) { print "${C_CYN}$_"; }
else { print "${C_RST}$_"; }
}
close($diff_fh);
print $C_RST;
}
# Overwrites the original file with the specified backup.
sub do_restore {
my $backup_file = resolve_target(shift);
if (!$backup_file \vert{}\vert{} !-e$backup_file) {
die "${C_RED}Backup file not found or invalid ID.${C_RST}\n";
}
my $orig_file =$backup_file;
$orig_file =~ s/\.\d{8}_\d{6}(?:\.\d+)?$//;
if (copy_file($backup_file,$orig_file)) {
print "${C_GRN}Restored successfully:${C_RST}$orig_file\n";
} else {
die "${C_RED}Failed to restore: $!${C_RST}\n";
}
}
# Deletes a backup file and updates the database list immediately.
sub do_rm {
my $backup_file = resolve_target(shift);
if ($backup_file && -e$backup_file) {
if (unlink($backup_file)) {
print "${C_GRN}Deleted backup:${C_RST}$backup_file\n";
do_list(); # Triggers DB cleanup automatically
} else {
die "${C_RED}Failed to delete$backup_file: $!${C_RST}\n";
}
} else {
die "${C_RED}Backup file not found or invalid ID.${C_RST}\n";
}
}
# ==============================================================================
# Helper Functions
# ==============================================================================
# Resolves a user argument (either an integer ID or a filepath) to an absolute path.
sub resolve_target {
my $target = shift;
# If the user provided a direct file path, return it immediately
return abs_path($target) if -f$target;
# If the user provided a number (ID), lookup in the DB
if ($target =~ /^\d+$/) {
open(my $fh, '<',$backups) or return undef;
my @items = <$fh>;
close($fh);
my $count = 0;
foreach my $line (@items) {
if ($line =~ m/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) (.+)$/s) {
my $file = $3;
chomp($file);
if (-s $file) {$count++;
return $file if $count ==$target; # Found the matching ID
}
}
}
}
return undef; # Target could not be resolved
}
# A fast, memory-efficient block-based file copy function (replaces File::Copy).
sub copy_file {
my ($src,$dest) = @_;
open(my $in, '<',$src) or return 0;
open(my $out, '>',$dest) or return 0;
my $buffer;
# Read and write in 8KB chunks
while (sysread($in,$buffer, 8192)) {
syswrite($out,$buffer);
}
close($in);
close($out);
return 1;
}
# Removes ANSI color codes from a string (useful for length calculations).
sub strip_ansi {
my $str = shift;
$str =~ s/\e\[[\d;]*[a-zA-Z]//g;
return $str;
}
# Pads a string with spaces to a specified length, ignoring ANSI color codes.
sub pad_ansi {
my ($str, $len,$align_right) = @_;
my $visible_len = length(strip_ansi($str));
my $spaces = $len -$visible_len;
$spaces = 0 if$spaces < 0;
return $align_right ? (" " x $spaces) .$str : $str . (" " x $spaces);
}
# Converts a byte size into a human-readable string (B, K, M, G, T) with colors.
sub format_bytes {
my $size = shift || 0;
my @units = qw(B K M G T);
my $i = 0;
while ($size >= 1024 && $i <$#units) {
$size /= 1024;
$i++;
}
my $val = ($i == 0 \vert{}\vert{}$size >= 10) ? sprintf("%d", $size) : sprintf("\%.1f", $size);
return $C_RST .$val . $C_GRN .$units[$i] .$C_RST;
}
# Calculates file age and formats it dynamically based on the elapsed time.
sub format_age_colored {
my $mtime = shift;
my $diff = time() -$mtime;
if ($diff < 60) {
return "${C_RED}$diff sec${C_RST}";
} elsif ($diff < 3600) {
my $m = int($diff / 60);
return "${C_PNK}" . ($m == 0 ? "< min" : "$m min") . "${C_RST}";
} elsif ($diff < 86400) {
return "${C_YLW}" . int($diff / 3600) . " hr${C_RST}";
} else {
return "${C_GRY}" . int($diff / 86400) . " day${C_RST}";
}
}
__END__
=head1 NAME
b - A simple yet powerful utility for backing up, managing, and comparing files.
=head1 SYNOPSIS
b <file_path>
b
b diff <ID|file_path>
b restore <ID|file_path>
b rm <ID|file_path>
b help
=head1 DESCRIPTION
C<b> is a zero-dependency Perl script designed to make local file backups incredibly
fast and easy. It automatically timestamps files, catalogs them in C<~/.brc>, and
provides an elegant, colorful CLI interface to review, compare (diff), restore, or
delete them.
The list function automatically cleans up missing files from the database.
=head1 COMMANDS
=over 4
=item B<b [file_path]>
Creates a backup of the specified file in the same directory, appending the
current date and time (e.g., C<.zshrc.20261029_173659>).
=item B<b> or B<b list>
Displays a color-coded table of all available backups, including their index ID,
creation date, age, size, and absolute path.
=item B<b diff [ID|file_path]>
Compares the specified backup with the original file using the system's C<diff>
command. Provides colorized output indicating additions and deletions. You can
use the index number shown in the list command instead of the full path.
=item B<b restore [ID|file_path]>
Overwrites the original file with the contents of the specified backup.
=item B<b rm [ID|file_path]>
Permanently deletes the specified backup file from the disk and removes its
entry from the database.
=item B<b help>
Shows a brief usage summary.
=back
=head1 DATABASE
All backups are tracked in C<$HOME/.brc>.
If a backup file is deleted manually (via standard C<rm>), the script will
automatically detect its absence during the next C<b list> call and purge
it from the database.
=head1 DEPENDENCIES
None. This script utilizes core Perl modules (C<Cwd>, C<POSIX>) and does not
require any external CPAN packages.
=head1 AUTHOR
Mindaugas Nefas (15 Jan 2014).
Refactored 2026
=head1 BUGS
None reported... yet.
=cut