How to use sudo in a Mac OS X terminal

From ArticleWorld


When using command-line applications in the OS X terminal, you will often find yourself having to modify files that you do not own, or doing other actions that require administrative privileges.

Apple's decision of disabling the root account, common on most Unix system, was quite controversial at its time. Nevertheless, the advantages in terms of security are important. This leaves you with the other (secure) alternative of working with administrator privileges: sudo.

There are two prerequisites for using sudo:

  • Your user must be allowed to have administrative privileges, and
  • You must know your administrative password.

In the first case, your system administrator decides. If you are a home user (and therefore do not have a system administrator for obvious reasons), chances are your user already has administrative privileges (i.e. the "Allow user to administer this computer" checkbox in the System Accounts, Preferences window is checked).

If you forgot your administrative password (which you shouldn't have done), you should refer to Apple Help for instructions on how to restore it.

How to use sudo

In short, you use sudo to execute commands with administrative privileges. For example:

sudo rm /System/somesystem.file

will invoke rm with administrative privileges.

You can type any command after sudo, but do remember that running multiple commands using ';' or '&&' as delimiters requires you to use sudo in front of any command.

By default, sudo will not ask you for a password five minutes after it has been invoked. This is done to prevent the hassle of typing the password every time, supposing that if you knew it the first time, you obviously know it after that. However, you should be careful if more users use your computer: they will be able to use sudo if you leave your computer unattended.

You can also use sudo to spawn a shell (i.e. launching a new shell, but with administrative privileges for the user). To do so, run:

sudo -s

Notes

You should obviously be extra careful when using sudo. It will not ask you for confirmations. Pressing enter will execute the specified command, regardless of whether it is what you want or whether it is correct or not. You can cause some damage to your system, so check everything before pressing Return.