Linux Bash 和 Windows Batch 的自删除脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7198281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 17:56:16  来源:igfitidea点击:

Self-Deleting Script for both Linux Bash and Windows Batch

windowsbashbatch-fileself-destruction

提问by George Hernando

I have an uninstall script that cleans up an add-on tool used with an application. Versions of the script run on both Windows and Linux.

我有一个卸载脚本,用于清理与应用程序一起使用的附加工具。该脚本的版本可在 Windows 和 Linux 上运行。

I'd like to be able to delete the uninstall script file and also the directory in which the script runs too (in both the case of a Windows batch file and also for the case of a Linux bash file). Right now everything but the script and the directory in which it runs remains after it runs.

我希望能够删除卸载脚本文件以及运行脚本的目录(对于 Windows 批处理文件和 Linux bash 文件)。现在,除了脚本和它运行的目录之外的所有内容在它运行后都保持不变。

How can I delete the script and the script's directory?

如何删除脚本和脚本目录?

Thanks

谢谢

回答by michel-slm

In Bash, you can do

在 Bash 中,你可以这样做

#!/bin/bash
# do your uninstallation here
# ...
# and now remove the script
rm 
#!/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=##代码##
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"
# and the entire directory rmdir `dirname ##代码##`

回答by brakertech

##代码##