2011-08-25 55 views
2

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

我希望能够删除卸载脚本文件以及脚本运行的目录(既包括Windows批处理文件,也包括Linux bash文件的情况)。现在,除了脚本和它运行的目录之外,其他所有的东西都保留下来。

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

感谢

回答

9

在bash中,你可以做

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

使用这个我能得到的脚本删除,但该目录似乎并没有删除,虽然我不没有看到错误。 –

+0

它在目录中还有其他或隐藏的文件吗? – leon

+1

正确;如果你确定目录可以被安全地删除,你可以使用''rm -rf'dirname $ 0''' –

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