Sometimes it is needed to check what user is executing the bash script and whether the user supplied all required arguments:

#!/bin/bash 
 
display_usage() { 
	echo "This script must be run with super-user privileges." 
	echo -e "\nUsage:\n$0 [arguments] \n" 
	} 
# if less than two arguments supplied, display usage 
	if [  $# -le 1 ] 
	then 
		display_usage
		exit 1
	fi 
 
# check whether user had supplied -h or --help . If yes display usage 
	if [[ ( $# == "--help") ||  $# == "-h" ]] 
	then 
		display_usage
		exit 0
	fi 
 
# display usage if the script is not run as root user 
	if [[ $USER != "root" ]]; then 
		echo "This script must be run as root!" 
		exit 1
	fi 
 
echo "All good !!!"

OUTPUT:

$ ./script.sh 1 
This script must be run with super-user privileges.

Usage: ./script.sh [arguments] 

$ su
Password: 
# ./script.sh 1 2
All good !!!

Free Linux eBooks

Linux Technical Writer

LinuxCareer, Casual, Volunteer, Home Based

Do you wish to join Linuxcareer.com project and find out how to be a technical writer? We are now looking for volunteers to help us write tutorials and share them with Linux community

  • Casual work from home
  • 10 articles / year

Any active Linuxcareer.com’s author will be entitled to following benefits:

  • actively participate in Linuxcareer.com’s decision making process
  • feedback and help

APPLY

Do you have the right skills?

Our IT Skills Watch page reflects an up to date IT skills demand leaning towards the Linux and Unix environment. We have considered a number of skills and operating systems.

See the result...

Linux Online Training

Learn to run Linux servers and prepare for LPI certification with Linux Academy. 104 available video lessons with PDF course notes with your own server!

Go to top