Self-Deleting Script for both Linux Bash and Windows Batch
Asked Answered
C

2

6

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.

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.

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

Thanks

Canny answered 25/8, 2011 at 23:14 Comment(0)
M
13

In Bash, you can do

#!/bin/bash
# do your uninstallation here
# ...
# and now remove the script
rm $0
# and the entire directory
rmdir `dirname $0`
Metallophone answered 25/8, 2011 at 23:19 Comment(4)
Using this I was able to get the script to delete, but the directory doesn't seem to delete, although I don't see an error.Canny
it there any other or hidden files in the directory?Denicedenie
Right; if you're really sure the directory can be safely deleted, you can just use rm -rf `dirname $0` Metallophone
Should there be a " around $0?Leavetaking
S
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"
Steinman answered 20/8, 2013 at 14:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.