Created
February 22, 2024 23:50
-
-
Save adfaklsdjf/b9cb2ec34662745e47f05ff0fb381ec7 to your computer and use it in GitHub Desktop.
copy files with a 'pv' progress bar and rate info
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Ensure that at least two arguments are provided (source(s) and destination) | |
if [ "$#" -lt 2 ]; then | |
echo "Usage: $0 <source1> [<source2> ...] <destination>" | |
exit 1 | |
fi | |
# The last argument is the destination | |
destination="${@: -1}" | |
# All arguments except the last one are considered sources | |
sources=("${@:1:$(($#-1))}") | |
echo "Destination directory: $destination" | |
echo "Source item(s): ${sources[*]}" | |
# Create the destination directory if it does not exist | |
echo "Ensuring that the destination directory exists..." | |
mkdir -p "$destination" | |
# Calculate total size for pv | |
echo "Calculating total size of source item(s) for progress estimation..." | |
local total_size=0 | |
if [[ ${#sources[@]} -eq 1 && -d ${sources[0]} ]]; then | |
total_size=$(du -sb "${sources[0]}" | cut -f1) | |
else | |
# Handling for multiple files or a glob pattern | |
# This calculation assumes all sources are in the same directory or the shell has expanded them correctly | |
total_size=$(du -cb "${sources[@]}" 2>/dev/null | tail -1 | cut -f1) | |
fi | |
echo "Total size to copy: $total_size bytes" | |
# Copy process | |
if [[ ${#sources[@]} -eq 1 && -d ${sources[0]} ]]; then | |
echo "Copying directory..." | |
tar -cf - -C "${sources[0]}" . | pv -s "$total_size" | tar -xf - -C "$destination" | |
else | |
echo "Copying multiple files/glob..." | |
sourcedir="$(dirname "${sources[0]}")" | |
tar -cf - -C "$sourcedir" "${sources[@]/#$sourcedir\//}" | pv -s "$total_size" | tar -xf - -C "$destination" | |
fi | |
echo "Copy operation completed successfully." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment