Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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/$username.zip ."

This works as expected.

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Then

sudo -u $username unzip /home/0-backup/users/$username.zip -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" ]
then
    sudo sh -c "cd '/home/$username' && rm -rf * .[^.]*"
fi

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading