Bash脚本中的回收站

时间:2016-11-29 18:27:00

标签: linux sh recycle-bin

我正在尝试使用bash脚本在VM中创建基本的回收站概念。它需要删除已输入的文件并将它们放入创建的目录中,并将路径(原点)保存到日志文件中,以便稍后在恢复功能中使用。

我将从我的删除/回收代码开始,我相信它工作得很好,但似乎有些不整洁/包含冗余代码:

#!/bin/sh  

if [ ! -d ~/recycle ]
then mkdir ~/recycle
fi

if [ ! -d ~/recycle/recycle_log ]
then mkdir ~/recycle/recycle_log
fi

if [ ! -d ~/recycle/recycle_bin ]
then mkdir ~/recycle/recycle_bin
fi

if [ -d ~/recycle ]
then
echo "$(readlink -f "$1")" >> "$HOME/recycle/recycle_log/log_file" && mv "$1" "$HOME/recycle/recycle_bin"
echo "$(readlink -f "$2")" >> "$HOME/recycle/recycle_log/log_file" && mv "$2" "$HOME/recycle/recycle_bin"
echo "$(readlink -f "$3")" >> "$HOME/recycle/recycle_log/log_file" && mv "$3" "$HOME/recycle/recycle_bin"
echo "$(readlink -f "$4")" >> "$HOME/recycle/recycle_log/log_file" && mv "$4" "$HOME/recycle/recycle_bin"
fi

#end

此后我的恢复脚本的内容如下:

#!/bin/sh

cd "$HOME/recycle/recycle_bin" || exit 1
mv -i "$(grep "$1" "$HOME/recycle/recycle_log")"

我想这有点接近我需要返回存储在日志/回收站中的任何已删除文件以恢复到其原点,但我得到的错误是:

mv: missing destination file operand after `'

关于我出错的地方的任何想法?

1 个答案:

答案 0 :(得分:0)

试试这个:

recycle.sh

#!/bin/sh  

set -e

check_dir() {
    [ ! -d $1 ] || return 0
    mkdir --parents $1
}

check_dir "${HOME}/recycle/recycle_bin"
touch "${HOME}/recycle/recycle_log"

for file in "$@"; do
    echo "$(readlink -f "$file")" >> "${HOME}/recycle/recycle_log"
    mv "$file" "${HOME}/recycle/recycle_bin"
done

#end

restore.sh

#!/bin/sh

set -e

cd "${HOME}/recycle/recycle_bin" || exit 1

for name in "$@"; do
    file=$(grep "\/${name}\$" "${HOME}/recycle/recycle_log")
    mv -i $name "$file"
    sed -i "/\/${name}\$/ d" "${HOME}/recycle/recycle_log"
done

一些见解:

set -e:中止任何错误,以避免一些if

$@:参数数组($ 1,$ 2 ......)

[ ! -d $1 ] || return 0:由于我们使用set -e,如果目录存在,请不要失败

grep "\/${name}\$" ...:仅匹配路径末尾的名称

sed -i:进行就地编辑以删除该行