How do I generate a script with an inverse action?

I have an interactive script which sorts and processes a variety of filetypes from an unsorted folder into newly created directories.

The script works great, But I was wondering how I could generate a script with an inverse action so that I could unwind / undo the executed script and its sorting process back to the folders (pre sort) state if need be.

What is the leanest possible way of achieving this.


#!/bin/bash
read -p "Good Morning, Please enter your file type name for sorting [ENTER]:" all_extensions
if cd /Users/christopherdorman/desktop
  then  while read extension
      do    destination="folder$extension"
        mkdir -p "$destination"
        mv  -v unsorted/*."$extension" "$destination"
      done   <<< "${all_extensions// /$'\n'}"
        mkdir -p foldermisc 
        if mv  -v unsorted/* "foldermisc"
      then  echo "Good News, the rest of Your files have been successfully processed"
        fi
    for i in folder*/; do
        ls -S "$i" > "${i}filelist" 
        cat "${i}filelist" >> ~/desktop/summary.txt
    done
fi

Hi.

Off the top of my head, I would create commands when you do the initial move. So for:

mv -v unsorted/*."$extension" "$destination"

I would create:

mv "$destination/*.$extension" unsorted

and save these in a file.

For an undo then you would execute the built script.

It would be more complex if you allowed several initial moves and then want to undo to a specific step.

Practice on test directories first.

Good luck ... cheers, drl

i run my file using ./script.txt

how do i run the inverse or call the inverse given the code you said is nested in the same script

cheers

Hi.

Suppose you collect the created lines in a file called inverse.txt:

mv foo bar
mv baz qux
...

then you could use:

bash inverse.txt

or, if you add execute permission, chmod +x inverse.txt , then:

./inverse.txt

Practice with a manually built file.

Best wishes ... cheers, drl