I want to execute a script that requires root privileges without entering a password. There are similar questions/answers but non seems to work for me.

I placed my script in /home/kf/bin (I added the bin dir myself) and included this directory in my path so I can run it from everywhere.

The script: trim.sh:

#! /bin/sh
sudo fstrim -v /

I changed the ownership of the script to root:

 sudo chown root:root /home/kf/bin/trim.sh

and made it executable

sudo chmod 700 /home/kf/bin/trim.sh

next I added a line to my sudoers file with visudo:

kf   ALL=(ALL) NOPASSWD: /home/kf/bin/trim.sh

When I login again and execute the script with trim I still need to enter my password. I know I can make a cron for this but I also want to be able to execute the script manually without entering my password. Any help appreciated.


My sudoers file looks like this:

Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin: /usr/bin:/sbin:/bin"

root    ALL=(ALL:ALL) ALL
kf   ALL=(ALL) NOPASSWD: /home/kf/bin/trim.sh

%admin ALL=(ALL) ALL
%sudo   ALL=(ALL:ALL) ALL

2 Answers 2


Change the line in the sudoers file to:

kf   ALL=(ALL) NOPASSWD: /sbin/fstrim

I don't recommend, adding the script in /etc/sudoers, because the script can be altered and every command (the whole script) would then be executed with root privileges.

  • well, that is not true because the file is owned by root so you can't edit it unless you know the password... that's why I changed the ownership to root. Aug 25, 2015 at 11:08
  • 2
    @kasperTaeymans That won't help. anyone can simply remove the script and replace with another one. Aug 25, 2015 at 11:09
  • @kasperTaeymans True, didn't see that in the question. But, anyway: only use root privileges when they are needed. They are only needed for the fstrim command.
    – chaos
    Aug 25, 2015 at 11:10
  • I quite agree with the fact that the script should be in a "save" location, but then the /etc/crontab is also ok. Edit: Ah, I see your point now :) Aug 25, 2015 at 11:10
  • @kasperTaeymans What Jacob Vlijm said is extremely correct: every file (even if owned by root) can be removed from the owner of the folder which contains it. You should move your script elsewhere
    – kos
    Aug 25, 2015 at 11:14

What you're looking for is the setuid bit, it allows the users to exec a program with the permissions of its owner.

/!\ Be careful with it, it's often a bad solution, due to the security problems it exposes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.