I have an interactive script which sorts and processes a variety of filetypes from an unsorted folder into newly created directories.I was wondering how I could write a small script or modify the existing script that 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/bashread -p Good Morning, Please enter your file type name for sorting [ENTER]: all_extensionsif 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    donefi
How do I generate a script with an inverse action
bash;shell script;sort
Below is a function that you could call after the (successful) mv commands, giving it the same parameters as you did for mv, and the function will echo out corresponding commands that should put the files back where they were. You could alternatively redirect these commands to a backout file; they are also commented out, just as a safety precaution.function mvbackout {  declare -a files  for f  do    files+=($f)  done  # remove the last parameter (the destination)  unset files[$(( $# - 1 ))]  dest=$f  printf # cd -- %s\n $PWD  for f in ${files[@]}  do    printf # mv -- '%s' '%s'\n ${dest}/$(basename $f) $f  done}The function (can't) recover from data-loss scenarios (where the initial mv command clobbered a file by accident; or a file was later moved or removed), but for the main idea, it should work.Important caveatBecause re-quoting shell commands back to the shell is tricky, I've surrounded the filenames with single quotes, which means that copy/pasting the resulting command will not work if any of the filenames in that command contains single quotes.Here's a sample run:$ mkdir dest$ touch a b$ mkdir -p subdir1/subdir2/subdir3 mkdir fun\'d\'ir fun\'d\'ir/fun\d\ir$ touch subdir1/c subdir1/subdir2/d subdir1/subdir2/subdir3/e $ mv a b subdir1/c subdir1/subdir2/d subdir1/subdir2/subdir3/e dest$ mvbackout a b subdir1/c subdir1/subdir2/d subdir1/subdir2/subdir3/e dest# cd -- /home/schaller/tmp/dir# mv -- 'dest/a' 'a'# mv -- 'dest/b' 'b'# mv -- 'dest/c' 'subdir1/c'# mv -- 'dest/d' 'subdir1/subdir2/d'# mv -- 'dest/e' 'subdir1/subdir2/subdir3/e'For your script, you could add another line after each mv, like so:...mv  -v unsorted/*.$extension $destinationmvbackout unsorted/*.$extension $destination... if mv  -v unsorted/* foldermiscthen   mvbackout unsorted/* foldermisc    echo Good News, the rest of Your files have been successfully processedfi