使用脚本执行撤消操作

时间:2016-11-29 20:55:01

标签: bash unix terminal

我有一个出色的交互式脚本,可以将未分类文件夹中的各种文件类型排序和处理到新创建的目录中。

我想知道如何编写一个小脚本或修改现有脚本,以便在需要时可以将执行的脚本及其排序过程解除/撤回到其(预排序)状态。

#!/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

1 个答案:

答案 0 :(得分:1)

如果您要为您正在执行的每项操作生成一个带有反向操作的脚本,请使用printf %qeval安全方式引用名称。例如:

if [[ $undo_log ]]; then
  # at the top of your script: open FD 3 as undo log
  exec 3>"$undo_log"
fi

# later:
mv  -v unsorted/*."$extension" "$destination"

# ...and, if we're generating an undo log, generate a sequence of appropriate commands
if [[ $undo_log ]]; then
  for f in unsorted/*."$extension"
    printf 'mv %q/%q %q\n' "$destination" "${f##*/}" "$f" >&3
  done
fi