Is it a bad practice to run a command which requires sudo in ~/.profile?

If really want to do that, how can I make the command run at rebooting Ubuntu?

  • make the command running with sudo and under my user account not require password, by editing /etc/sudoers?

  • provide my password in the command with sudo in ~/.profile, by echo <passwd> | sudo -S <mycommand>?

I haven't verified if the first way works, because I am still learning how to do it.

The second way seems to raise serious security concern, and probably the least way I want to go.



If you put the command in your ~/.profile, it will run every time you launch a login shell. Some terminal emulators allow you to use a login shell for each terminal window. Do you want your command running that often?

If you want to be allowed to use sudo for that command without entering a password, use the visudo command with sudo visudo (or, to use your favourite editor, use sudo -E visudo).
DO NOT EDIT /etc/sudoers DIRECTLY.

Add a line like this:

tim  ALL=(ALL) NOPASSWD: /path/to/my/command

The order is important in the sudoers file, so add it below this line: root ALL=(ALL:ALL) ALL

However, if you only want it to run when your system starts up, add it to /etc/rc.local and you don't have to worry about sudo.

  • Thanks! Curious why "DO NOT EDIT /etc/sudoers DIRECTLY"? How differently does visudo work from editing the file directly? – Tim Apr 1 '18 at 14:36
  • 1
    @Tim From man visudo: "visudo locks the sudoers file against multiple simultaneous edits, provides basic sanity checks, and checks for parse errors.". You definitively do not want /etc/sudoers get corrupted, recovering from such a situation is a hassle. – nohillside Apr 1 '18 at 14:38
  • @patrix Thanks. I am probably not going to try the dangerous sudoers way. May I still ask about it? If the command I want to run in ~/.profile is a bash script which contains a command which needs root privillege, do I need to add both the script and the command in it to /etc/sudoers, or just the script? – Tim Apr 1 '18 at 15:03
  • Just the script. Once you launch the script with elevated privs, commands called from it have the same privs. – glenn jackman Apr 1 '18 at 15:25
  • But, how often do you need to run this command? Once at startup or every login shell? – glenn jackman Apr 1 '18 at 15:25

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.