Merging subdirectories while moving files using "mv"
The command line executable mv
cannot merge subdirectories. It will fail with messages like mv: cannot move: Directory not empty
The following is a bash script to move all contents of "SRC" directory to "DEST" directory. The usage is ./merge-mv SRC DEST
✅
As always, use with your own risk.
#!/usr/bin/env bash
set -eu
shopt -s globstar
shopt -s dotglob
shopt -s nullglob
src_path=$(readlink -f "$1")
dst_path=$(readlink -f "$2")
cd "${src_path}"
for dir in **/; do
if [[ ! -e "${dst_path}/${dir}" ]]; then
mv -nv "${dir}" "${dst_path}/${dir}"
continue
fi
if [[ ! -d "${dst_path}/${dir}" ]]; then
>&2 echo "Cannot merge '${src_path}/${dir}' with '${dst_path}/${dir}'"
exit 1
fi
done
for dir in **/; do
for file in "${dir}"*; do
if [[ -d "${file}" ]]; then
continue
fi
mv -nv "${file}" "${dst_path}/${dir}"
done
done
find . -mindepth 1 -type d -delete
If there is a conflict, the script will not overwrite existing file in DESR and let the conflicting file in SRC stay as-is. Feedbacks are welcome (contact me at https://mastodon.jangho.io/@jangho)