2011-08-25 23 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"