

On the other hand, when you need to affect settings or processes in a user’s context or login session, you may need to run commands as a specific user from a script running as root. Most administrator scripts are run in a context where they run with super user privileges. >&2 echo "script requires super user privileges, exiting." As usual with Unix, there are many ways to achieve this, but the recommended one is to check the EUID (effective user id) environment variable.

When you write scripts that require root privileges, you may want to test whether it is actually running as root early in the script or exit gracefully with an error or warning. (Remote Desktop: run as user root, installation scripts, LaunchDaemons, management systems, etc.) Testing for root Privileges in Scripts Or you deploy and execute the script through other methods that provide root privileges. When commands inside a script require root privileges, you should invoke the entire script with sudo: $ sudo. You should not use sudo in your management scripts. Systemsetup -setnetworktimeserver "$timeserver" In most contexts, the scripts should already be running with root privileges so sudo in the script is not necessary. However, when this script is sent with Remote Desktop or run in a different context without user interaction to authorize sudo, the script will stall and eventually fail. In many cases where the script already has root privileges, it will work also, because sudo when run as root will not prompt for authorization again. When you invoke this script from the command line, it will actually work as expected, since the first sudo will prompt the password and the second sudo will use the cached credentials. Sudo systemsetup -setnetworktimeserver "$timeserver" For example: #!/bin/bashĮcho "Setting Time Server to: $timeserver" Many novice scripters will simply add the sudo command to their scripts. You will write scripts that require root privileges to perform their tasks. However, when you are scripting workflows then you don’t want to encounter the interactive prompt for authentication. Sudo is very useful when working interactively in the shell.
