'Shell: Move file and folder listed in a list
I'm using Alpine Linux and would like to move specified files and folders from a list. My final goal being to reset a folder by making a backup of some files and folders inside it.
Here is my current script:
cd /mnt/server
mkdir /tmp/backup
[ -d folderOne ] && mv folderOne /tmp/backup
[ -f fileOne.txt ] && mv fileOne.txt /tmp/backup
rm -fr *
rm -fr .*
[ -d /tmp/backup/folderOne ] && mv /tmp/backup/folderOne /mnt/server
[ -f /tmp/backup/fileOne.txt ] && mv /tmp/backup/fileOne.txt /mnt/server
rm -fr /tmp/backup
I would like to use a list to avoid script redundancy and use as few external software as possible. So the idea would be to have a list containing the path to the folders and files to backup. I would use a for loop to go through the list and, if the file/folder exists, then move it by recreating the hierarchy if necessary.
folder/folder2/file.txt would recreate the missing folders and place the file there. And if it is a folder (folder/folderTwo) then it recreates the missing hierarchy and places the folder (and its contents) in it.
Solution 1:[1]
#! /bin/bash
set -eu
workdir=/mnt/server
cd "$workdir"
mkdir /tmp/backup
movables=(folderOne fileOne.txt folder/folder2/file.txt)
for move in "${movables[@]}" ; do
if [[ -d $move || -f $move ]] ; then
if [[ "$move" = */* ]] ; then
mkdir -p /tmp/backup/"${move%/*}"
fi
mv "$move" /tmp/backup/"${move%/*}"
fi
done
shopt -s extglob
rm -fr !(.|..)
find /tmp/backup
for move in "${movables[@]}" ; do
if [[ -d /tmp/backup/$move || -f /tmp/backup/$move ]] ; then
if [[ "$move" = */* ]] ; then
mkdir -p "$workdir/${move%/*}"
fi
mv /tmp/backup/"$move" "$workdir"
fi
done
rm -fr /tmp/backup
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
