Files
q-tools/files/cp-progress
2019-04-12 13:46:41 +03:00

79 lines
1.8 KiB
Bash
Executable File

#!/bin/bash
set -e
function helpexit() {
echo Usage: $( basename "$0" ) [--nc] source [source] target
echo Copy files with a progress bar to a folder.
echo This command always
echo '* recurses to folders!'
echo '* overwrites existing files'
echo '--nc Dont count bytes first'
exit
}
SRC=( )
for ((i=1; i<=${#@}; i++)) {
[[ "${!i}" = "-h" ]] && helpexit
[[ "${!i}" = "--help" ]] && helpexit
[[ "${!i}" = "--nc" ]] && { NOCOUNT=1; continue; }
# [[ "${!i}" = "-"* ]] && helpexit
SRC+=( "${!i%/}" )
}
[[ "${#SRC[@]}" -lt 2 ]] && helpexit
which pv &> /dev/null || { echo No \'pv\' installed; exit 1; }
TGT=${SRC[${#SRC[@]}-1]}
unset 'SRC[${#SRC[@]}-1]'
for path in ${SRC[@]}; do
[[ -e "$path" ]] || { echo $path missing; exit 1; }
done
getsize() {
if [[ "$NOCOUNT" -eq 1 ]]; then
echo 0
else
fastdu -s "$@"
fi
}
copy_file() {
pv "$1" > "$2"
chmod --reference="$1" "$2"
chown --reference="$1" "$2"
}
copy_dir() {
mkdir -p "$2"
chmod --reference="$1" "$2"
chown --reference="$1" "$2"
mysize=$( getsize "$1" )
TGT_ABS=$( abs-path "$2" )
pushd "$1" &> /dev/null
tar -c "." | pv -s $mysize | tar -x --strip-components=1 -C "$TGT_ABS"
popd &> /dev/null
}
copy_to() {
if [[ -f "$1" ]]; then # file to folder
copy_file "$1" "$2"
else # folder to folder
copy_dir "$1" "$2"
fi
}
if [[ ${#SRC[@]} -eq 1 ]]; then # only one input
if [[ ! -d "$TGT" ]]; then # target is not a (existing) dir
copy_to "${SRC[0]}" "$TGT"
exit $?
fi
fi
# Otherwise, create folder, and copy in it
[[ -f "$TGT" ]] && { echo Copying multiple sources: Target can only be a folder; exit 1; }
mkdir -p "$TGT"
for SRC_THIS in "${SRC[@]}"; do
SRC_BASE=$( basename "$SRC_THIS")
echo "$SRC_THIS"
copy_to "$SRC_THIS" "$TGT"/"$SRC_BASE"
done