Go · lesson 23 of 30 · Files and errorsCopy a file with a date
time.Now().Format makes the name, io.Copy copies and O_EXCL never overwrites a file.
23-dated-backup.go Download 23-dated-backup.go
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
)
// Copies one file into backups/ under a name with the date and time
func backup(source string) (string, int64, error) {
in, err := os.Open(source)
if err != nil {
return "", 0, err
}
defer in.Close()
if err := os.MkdirAll("backups", 0o755); err != nil {
return "", 0, err
}
ext := filepath.Ext(source)
name := strings.TrimSuffix(filepath.Base(source), ext)
target := filepath.Join("backups", name+time.Now().Format("-2006-01-02-150405")+ext)
out, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
if err != nil {
return "", 0, err
}
n, err := io.Copy(out, in)
if closeErr := out.Close(); err == nil {
err = closeErr
}
if err != nil {
os.Remove(target) // no half copy stays
}
return target, n, err
}
func main() {
if len(os.Args) != 2 {
fmt.Println("usage: 23-dated-backup FILE")
os.Exit(2)
}
target, n, err := backup(os.Args[1])
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(n, "bytes to", target)
}
Terminal
$ ./23-dated-backup words.txt
87 bytes to backups/words-2026-11-25-140810.txt
$ cmp words.txt backups/words-*.txt && echo "the copy is the same"
the copy is the sameThe numbers or the date differ on your NAS.
Exercise
Keep only the newest three copies.
TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.