Shell is an interpreter that interprets commands from a file or an input device like keyboard. There are many shells available for programmers, end users and admins, like sh, tsh, csh, bash and many more.
Most popular and user-friendly shell now- a-days is Bash (Bourne Again shell) that was written by Stephen Bourne at Bell Labs.
Shell scripting starts with shebang, which tells operating system as to which binary is to be used as an interpreter for the script.
Shebang for Bash shell looks as follows:
#!/bin/bash
Any regular work that’s done using a command-line by admins or users can be transformed into a shell script for simplifying their regular tasks.
To write a script, any text editor can be used.
So here we start it by taking a sample example:
Just open a text editor and write the following, save changes with sample testfile as name
#!/bin/bash
# echo command is used to just print “Message written in this quote” on Standard Output i.e. on terminal or screen.
echo “Hello ZNET”
Run/execute the sample script with shell command as:
root~]# bash testfile
Here we have used # character to comment on our sample code. It is a good practice to write comments for each line or segment of code as it helps other admins or users to understand what this scriptlet or code will do.
Linux shell script writers have good knowledge of command line and are knowledgeable enough to write the script.
A script generally consists of variable/keywords/data_types/conditional_statements/commands/comments/cases etc. just like any other programming or scripting language. Style may be different but logics and conceptual flows behind them are nearly the same.
Another example:
Shell script for those Linux admins who are cautious of server CPU load and wish to get an alert whenever the CPU load exceeds a specific value.
Just write it with any text editor, save changes and set this script to be run in every 2 minutes with the help of scheduling task programme i.e. Cron Job.
#!/bin/bash
### Shell script to check CPU load average and get alerts via mail whenever the CPU load exceeds value 10 ####
#### Variable CPULOAD defined and given constant value ####
CPULOAD=”10″
#### Variable LOADAVG defined which stores whatever is the output of the command ####
#### Command in turn reads and refines the specific output to a single numeric value ####
LOADAVG=$( cat /proc/loadavg |awk ‘{print $1 }’ |cut -d”.” -f1 )
#### Conditional If statement ####
#### It compares and decides the LOADAVG value and if it’s greater than or equal to CPULOAD value, then it throws a mail to admin at email ID [email protected] ####
if [ $LOADAVG -ge $CPULOAD ]
then
mail -s ” $HOSTNAME CPU LOAD ALERT Avg=$LOADAVG ” [email protected]
That’s it admins! Have fun writing scripts to ease your work. 🙂
Do drop your feedback in comments section.
Services ZNetLive offer: