NASutils Knowledge BaseUnofficialPolski

Bash · projectCopy a folder with a progress bar

This script copies a folder and shows how far it is: a bar, the bytes copied, the speed and the time left. With -l it keeps to a speed limit, so a big copy leaves the NAS quick for everyone else. If you stop it with q or Ctrl+C, it removes the file it was copying, so the destination holds only whole files.

Programming on the NAS › Bash in 30 lessons

  Copy progress → backup

  3 files, 192.0 KiB
  █████████████████████████████████░░░░░░░░░░░░░░░░░  66 %
  128.0 KiB of 192.0 KiB   32.0 KiB/s   0:02 left
  part2.bin
The copy of a sample folder of 3 files (192 KiB) at 32 KiB/s: 128 KiB copied, 66 %, 2 seconds left, now part2.bin.
  Copy progress → backup

  3 files, 192.0 KiB
  █████████████████████████████████░░░░░░░░░░░░░░░░░  66 %
  128.0 KiB of 192.0 KiB   32.0 KiB/s   0:02 left
  part2.bin

  Removed the half-copied file backup/part2.bin.
  Stopped. 2 of 3 files copied, 128.0 KiB.
After q: the half-copied part2.bin is removed, and 2 of 3 files are in the destination.

Download it on the NAS

curl -fsSLO https://kb.nasutils.net/projects/bash/progress.sh

progress.sh Download progress.sh

#!/usr/bin/env bash
# progress.sh: copies a folder with a progress bar, the bytes copied, the speed and the time left. A spinner turns
# while it counts the files. q or Ctrl+C stops the copy and removes the half-copied file.
# Run it: bash progress.sh [-l KIB_PER_SECOND] SOURCE DESTINATION   (-l limits the speed, so the NAS stays quick)
# It needs Bash 4 or newer, such as TurboShell's bash. With NOW set, the clock counts the planned time of each block.
set -uo pipefail
shopt -s globstar nullglob

A=$'\e[38;5;214m' G=$'\e[32m' R=$'\e[31m' D=$'\e[2m' B=$'\e[1m' N=$'\e[0m'
limit=0
[[ ${1:-} == -l ]] && limit=$2 && shift 2
(($# == 2)) || { echo "Usage: bash progress.sh [-l KIB_PER_SECOND] SOURCE DESTINATION" >&2 && exit 2; }
src=${1%/} dst=${2%/}
files=() sizes=() total=0 done_bytes=0 copied=0 current='' fake_us=0 start_us=0

kib() { # BYTES: the size in KiB or MiB with one decimal
  if (($1 < 1048576)); then printf '%d.%d KiB' $(($1 / 1024)) $(($1 % 1024 * 10 / 1024)); else
    printf '%d.%d MiB' $(($1 / 1048576)) $(($1 % 1048576 * 10 / 1048576))
  fi
}

clock_us() { # the time in microseconds; with NOW set, the planned time of the blocks copied so far
  if [[ -n ${NOW:-} ]]; then echo "$fake_us"; else echo "${EPOCHREALTIME//[!0-9]/}"; fi
}

stop() { # STATUS: the end after q or Ctrl+C; the file being copied goes, because it is not whole
  [[ -n $current ]] && rm -f "$current" && printf '\n  %sRemoved the half-copied file %s.%s' "$R" "$current" "$N"
  printf '\n  %sStopped.%s %d of %d files copied, %s.\e[?25h\n' "$B" "$N" "$copied" "${#files[@]}" "$(kib "$done_bytes")"
  exit "$1"
}
trap 'stop 130' INT
trap 'printf "\e[?25h"' EXIT

draw() { # NAME: the bar, the numbers and the file, three lines that are redrawn in place
  local pct=$((total ? done_bytes * 100 / total : 100)) w=50 full fill rest us speed=0 left='--:--'
  us=$(($(clock_us) - start_us))
  ((us > 0)) && speed=$((done_bytes * 1000000 / us))
  ((speed > 0)) && left=$(printf '%d:%02d' $(((total - done_bytes) / speed / 60)) $(((total - done_bytes) / speed % 60)))
  full=$((pct * w / 100))
  printf -v fill '%*s' "$full" ''
  printf -v rest '%*s' $((w - full)) ''
  printf '\e[3F\e[2K  %s%s%s%s%s %3d %%\n' "$G" "${fill// /█}" "$D" "${rest// /░}" "$N" "$pct"
  printf '\e[2K  %s of %s   %s%s/s%s   %s left\n' "$(kib "$done_bytes")" "$(kib "$total")" "$A" "$(kib "$speed")" "$N" "$left"
  printf '\e[2K  %s%s%s\n' "$D" "$1" "$N"
}

printf '\e[?25l\n  %sCopy%s %s → %s\n\n' "$B$A" "$N" "$src" "$dst"
spin=(⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏)
for f in "$src"/**; do # count the files first, so the bar knows the whole
  [[ -f $f ]] || continue
  files+=("$f")
  sizes+=("$(stat -c %s "$f")")
  total=$((total + sizes[-1]))
  printf '\r  %s%s%s Counting files: %d' "$A" "${spin[${#files[@]} % 10]}" "$N" "${#files[@]}"
done
printf '\r\e[2K  %d files, %s\n\n\n\n' "${#files[@]}" "$(kib "$total")"

chunk=1024 # KiB per block; with a limit, one block per second at most
((limit > 0 && limit < chunk)) && chunk=$limit
start_us=$(clock_us)
for i in "${!files[@]}"; do
  f=${files[i]} out=$dst/${files[i]#"$src"/}
  mkdir -p "${out%/*}"
  : >"$out"
  current=$out
  for ((k = 0; k * chunk * 1024 < sizes[i]; k++)); do
    if ((limit > 0)); then # wait the time this block may take, and listen for q meanwhile
      ms=$((chunk * 1000 / limit))
      IFS= read -rsn1 -t "$((ms / 1000)).$(printf '%03d' $((ms % 1000)))" key && [[ $key == q ]] && stop 0
      fake_us=$((fake_us + ms * 1000))
    elif read -t 0; then
      IFS= read -rsn1 key && [[ $key == q ]] && stop 0
    fi
    dd if="$f" of="$out" bs="${chunk}K" skip="$k" seek="$k" count=1 conv=notrunc 2>/dev/null
    n=$((sizes[i] - k * chunk * 1024)) # the last block of a file may be shorter
    done_bytes=$((done_bytes + (n < chunk * 1024 ? n : chunk * 1024)))
    draw "${f#"$src"/}"
  done
  current='' copied=$((copied + 1))
done
printf '  %sDone.%s %d files, %s.\n' "$G" "$N" "$copied" "$(kib "$total")"

What you learn

  • trap 'stop 130' INT runs your own function on Ctrl+C, here to remove the half-copied file.
  • \e[3F moves the cursor three lines up, so the same three lines show the newest numbers.
  • read -rsn1 -t 1 waits for a key for up to a second, which makes the speed limit and the q key one line.
  • shopt -s globstar lets "$src"/** list every file in every subfolder, sorted by name.
  • dd ... skip=K seek=K count=1 conv=notrunc copies block K of a file and leaves the blocks before it alone.

How it works

First the script counts. It walks through every file under the source with **, keeps the names and the sizes from stat -c %s, and turns a spinner on the same line for each file it finds. When the walk ends, it prints the number of files and their total size, and leaves three empty lines for the progress.

Then it copies each file in blocks of 1 MiB, or of the limit when the limit is smaller. With a limit, it waits before each block as long as that block may take: 32 KiB at 32 KiB/s is one second. It waits with read -t, so a q pressed in that second stops the copy at once. Without a limit, read -t 0 only checks whether a key is waiting.

After each block, draw jumps back three lines and redraws the bar, the numbers and the name of the file. The speed is the bytes copied divided by the time since the start; the time left is the rest divided by that speed. stop removes the file in current, which is set while a file is being copied and empty when it is whole. q ends the script with status 0, Ctrl+C with 130, the usual status after Ctrl+C.

Notes to the lines

  • 11-l with its number comes first; shift 2 removes both, so $1 and $2 are the folders.
  • 22–24The clock in microseconds from $EPOCHREALTIME. With NOW set, as in the test, the clock counts the planned time of each block, so the speed and the time left are the same in every run.
  • 26–31stop and the trap: remove the unfinished file, print what was copied, end with the status given.
  • 35–38The percentage, the speed in bytes per second and the time left as minutes and seconds.
  • 42–44Three lines redrawn in place; \e[2K clears each line before it is written.
  • 49–55The count with a spinner of ten braille signs; sizes[-1] is the size just added.
  • 64–65The destination file starts empty and is the current one until its last block is copied.
  • 69The wait of one block, which is also the listening for q.
  • 74dd copies one block into place; conv=notrunc keeps the part of the file copied before.

Run it

bash progress.sh -l 10240 /share/Public/photos /share/Backup/photos

The example copies at most 10 MiB/s (10240 KiB/s). Leave out -l to copy at full speed. q or Ctrl+C stops the copy. The script needs Bash 4 or newer; in TurboShell, bash in an SSH window is Bash 5.3.

Try it yourself

Print the time the copy took after "Done.", from start_us and clock_us. Add a check that the destination has room: compare total with the free space from df -k.

More projects in Bash