Merge branch 'master' of feistymeow.org:feisty_meow
[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 #hmmm: extract to a terminal size function.
8 # calculate the number of columsn in the terminal.
9 cols=$(stty size | awk '{print $2}')
10
11   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
12 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))
13   echo
14   echo "Example Usage:"
15   echo 
16   echo "$(basename $0 .sh) backup_copy original_folder"
17   echo
18   echo " ==> Deletes any files in backup_copy that are not found in original_folder." 
19   echo 
20 }
21
22 if [ $# -lt 2 ]; then
23   print_instructions
24   echo "There were not enough parameters provided to the script."
25   exit 1
26 fi
27
28 here="$1"; shift
29 there="$1"; shift
30
31 if [ ! -d "$there" -o ! -d "$here" ]; then
32   print_instructions
33   echo "One of the directories specified does not exist."
34   exit 1
35 fi
36
37 here_temp_file="$(mktemp "$TMP/remover_list.XXXXXX")"
38 there_temp_file="$(mktemp "$TMP/remover_list.XXXXXX")"
39
40 # find all the files in both hierarchies.
41 pushd "$here" &>/dev/null
42 find "." -type f | sort >"$here_temp_file"
43 popd &>/dev/null
44 pushd "$there" &>/dev/null
45 find "." -type f | sort >"$there_temp_file"
46 popd &>/dev/null
47
48 whack_list="$(mktemp "$TMP/remover_list.XXXXXX")"
49
50 comm -23 "$here_temp_file" "$there_temp_file" >"$whack_list"
51
52 while read input_text; do
53   if [ -z "$input_text" ]; then break; fi
54   herename="$here/$input_text"
55   rm -v "$herename"
56 done <"$whack_list"
57
58 # clean up.
59 rm "$whack_list" "$here_temp_file" "$there_temp_file"
60