How to delete contents of user home dir safely via bash


I am writing a bash script to do a account restore. The contents of the home dir is zipped up using this command.

sudo sh -c "cd /home/$username; zip -0 -FS -r -b /tmp /home/0-backup/users/$ ."

This works as expected.

If the user requests a restore of their data, I am doing the following

sudo sh -c "cd /home/$username; rm -rf *"


sudo -u $username unzip /home/0-backup/users/$ -d /home/$username/

This works as expected.

However you can see the flaw in the delete statement, if the username is not set. We delete all users home dir. I have if statements that do the checking to make sure the username is there. I am looking for some advice on a better way to handle resetting the users account data that isn’t so dangerous.

One thought I had was to delete the user account and then recreate it. Then do the restore. I think that this would be less risky. I am open to any suggestions.

>Solution :

Check the parameters first.

Then use && after cd so that it won’t execute rm if the cd fails.

if [ -n "$username" ] &&  [ -d "/home/$username" ]
    sudo sh -c "cd '/home/$username' && rm -rf * .[^.]*"

I added .[^.]* in the rm command so it will delete dot-files as well. [^.] is needed to prevent it from deleting . (the user’s directory) and .. (the /home directory).

Leave a Reply Cancel reply