Merge branch 'release-2.140.99'
[feisty_meow.git] / scripts / files / remove_here_if_not_there.sh
1 #!/bin/bash
2
3 function print_instructions()
4 {
5   echo -e "\n$(basename $0 .sh):\n"
6
7   # calculate the number of columsn in the terminal.
8   local cols=$(get_maxcols)
9
10   echo -e 'this script takes two parameters, a "here" folder and a "there" folder, almost as if it were a copy command.  but instead, this removes any file from under the "here" location if it cannot be found in the "there" location.  so the "there" location is considered a more definitive template of what should be in "here", such that we strip out what "there" does not have.\n\n
11 the most" useful way to use this script is for a "here" hierarchy that is a copy of an older version of another "there" hierarchy.  the "there" hierarchy may have changed a lot, including new files, changed files, and deleted files.  it is a simple operation to copy everything from "there" into "here" (such as by using the command [ cp -R "$there"/* "$here" ] ) , but it is a lot harder to determine what stuff in "here" is out of date and should be removed.  that is where this script comes in; it can be run to flush out any older things in "here", rather than requiring the user to manually find all those files.  ' | splitter --maxcol $(($cols - 1))
12   echo
13   echo "Example Usage:"
14   echo 
15   echo "$(basename $0 .sh) backup_copy original_folder"
16   echo
17   echo " ==> Deletes any files in backup_copy that are not found in original_folder." 
18   echo 
19 }
20
21 if [ $# -lt 2 ]; then
22   print_instructions
23   echo "There were not enough parameters provided to the script."
24   exit 1
25 fi
26
27 here="$1"; shift
28 there="$1"; shift
29
30 if [ ! -d "$there" -o ! -d "$here" ]; then
31   print_instructions
32   echo "One of the directories specified does not exist."
33   exit 1
34 fi
35
36 here_temp_file="$(mktemp "$TMP/remover_list.XXXXXX")"
37 there_temp_file="$(mktemp "$TMP/remover_list.XXXXXX")"
38
39 # find all the files in both hierarchies.
40 pushd "$here" &>/dev/null
41 find "." -type f | sort >"$here_temp_file"
42 popd &>/dev/null
43 pushd "$there" &>/dev/null
44 find "." -type f | sort >"$there_temp_file"
45 popd &>/dev/null
46
47 whack_list="$(mktemp "$TMP/remover_list.XXXXXX")"
48
49 comm -23 "$here_temp_file" "$there_temp_file" >"$whack_list"
50
51 while read input_text; do
52   if [ -z "$input_text" ]; then break; fi
53   herename="$here/$input_text"
54   rm -v "$herename"
55 done <"$whack_list"
56
57 # clean up.
58 rm "$whack_list" "$here_temp_file" "$there_temp_file"
59