• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Check if user is root/sudo before running a script

Check if user is root/sudo before running a script

Sometimes a script may need to only be run as root or using sudo, or run ensuring that it is not being run by root or using sudo. This quick post shows how to check if it’s the root user and exit the script.

File Permissions

The best way to make it that the script can only be run by root is to change ownership of the file to the root user and make it so only root can execute it. To change "myscript" to only run as root using filesystem permissions do this:

chown root myscript
chmod 0744 myscript

The above commands need to be run as the root user or using sudo. The chmod command makes it so all other users can still read the script but not execute it. To make it so they cannot read it either then do this:

chmod 0700 myscript

In the script

Sometimes you may want to move the checking into the shell script itself. This is also possible. Add the following to the start of the script to only allow root or sudo access:

if [ `whoami` != root ]; then
    echo Please run this script as root or using sudo
    exit
fi

To make it so only non-root users should run the script do this:

if [ `whoami` = root ]; then
    echo Please do not run this script as root or using sudo
    exit
fi

Check Out These Related posts:

  1. Chmod 777 Tutorial
  2. Add user to sudoers
  3. Add User To Group Linux
  4. Check if a PHP script is already running

Filed Under: Linux/Unix/BSD

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap