适用于Linux Bash和Windows Batch的自删除脚本

6
我有一个卸载脚本,用于清理应用程序中使用的附加工具。该脚本的版本在Windows和Linux上运行。
我想能够删除卸载脚本文件以及脚本运行的目录(无论是Windows批处理文件还是Linux bash文件)。现在,在脚本运行后,除了脚本和它运行的目录之外,其他所有东西都会保留。
如何删除脚本和脚本所在的目录?
谢谢
2个回答

13

在 Bash 中,你可以这样做:

#!/bin/bash
# do your uninstallation here
# ...
# and now remove the script
rm $0
# and the entire directory
rmdir `dirname $0`

使用这个方法,我成功地让脚本删除了,但是目录似乎没有被删除,尽管我没有看到任何错误。 - George Hernando
目录中是否有其他或隐藏文件? - Leon
3
好的,如果您确信该目录可以安全删除,您可以使用“rm -rf dirname $0”来删除目录。请注意,此命令会永久性地删除目标目录及其所有内容,因此请谨慎操作。 - michel-slm
$0 周围应该加上 " 吗? - mafu

4
#!/bin/bash
#
# Author: Steve Stonebraker
# Date: August 20, 2013
# Name: shred_self_and_dir.sh
# Purpose: securely self-deleting shell script, delete current directory if empty
# http://brakertech.com/self-deleting-bash-script

#set some variables
currentscript=$0
currentdir=$PWD

#export variable for use in subshell
export currentdir

# function that is called when the script exits
function finish {
    #securely shred running script
    echo "shredding ${currentscript}"
    shred -u ${currentscript};

    #if current directory is empty, remove it    
    if [ "$(ls -A ${currentdir})" ]; then
       echo "${currentdir} is not empty!"
    else
        echo "${currentdir} is empty, removing!"
        rmdir ${currentdir};
    fi

}

#whenver the script exits call the function "finish"
trap finish EXIT

#last line of script
echo "exiting script"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接