wiki:Csle2022/Agenda/scriptingandgithub

Hands-On

Linux programming (scripting)

Shell Scripting is the language of the linux terminal, sometimes referred to as “shebang” which is derived from the “#!” notation.

Shell scripts are executed by interpreters present in the linux kernel.

Typical operations performed by shell scripts include file manipulation, program execution, and printing text.

How to Write Shell Script in Linux/Unix

  • Create a file using a vi editor(or any other editor). Name script file with extension . sh.
  • Start the script with #! /bin/sh.
  • Write some code.
  • Save the script file as filename.sh.
  • For executing the script type bash filename.sh.

File Color : Executable scripts appear in a different colour from rest of the files and folders.

Let's start to have some experience on scripting

Simple Script for newbies

First we have to create a text file

$cat > hello.sh

And create the content in it

#!/bin/sh 
echo 'Hello World'

#!/bin/sh is "how to run" the program. echo 'Hello World' is "what to do" in the script

Then make the file executable

$ chmod +x hello.sh

And run the executable file

$./hello.sh

Output:

Hello world

Make yourself familiar with man man and man apropos on the shell. It will need for your self-tutoring.

Let's make this little advanced

How to define variables =

Variables can be defined using the syntax variable_name=value. To get the value of the variable, add $ before the variable

#!/bin/bash
# A simple variable example
greeting=Hello
name=world
echo $greeting $name

Arithmetic Expressions

These are the operstors supported by bash for mathematical calculations.

+	addition
-	subtraction
*	multiplication
/	division
**	exponentiation
%	modulus

Numerical expressions can also be calculated and stored in a variable using the syntax below:

value=$((expression))

#!/bin/bash

var=$((3+9))
echo $var

How to read user input

Sometimes user input are needed to perform relevant operations.

In bash, user inputs are taken using the read command.

read variable_name

To prompt the user with a custom message, use the -p flag.

read -p "Enter your age" variable_name

Numeric Comparison logical operators

Comparison is used to check if statements evaluate to true or false.

Equality   	                num1 -eq num2	is num1 equal to num2
Greater than equal to	num1 -ge num2	is num1 greater than equal to num2
Greater than	                num1 -gt num2	is num1 greater than num2
Less than equal to	        num1 -le num2	is num1 less than equal to num2
Less than	                num1 -lt num2	is num1 less than num2
Not Equal to	                num1 -ne num2	is num1 not equal to num2

Syntax:

if [ conditions ]
    then
         commands
fi

Conditional Statements (Decision Making)

Conditions are expressions that evaluate to a boolean expression (true or false). To check conditions, we can use if, if-else, if-elif-else and nested conditionals.

Conditional Statements:

There are total 5 conditional statements which can be used in bash programming

  • if statement
  • if-else statement
  • if..elif..else..fi statement (Else If ladder)
  • if..then..else..if..then..fi..fi..(Nested if)
  • switch statement

if statement

This block will process if specified condition is true.

Syntax:

if [ expression ]
then
   statement
fi

if-else statement

If specified condition is not true in if part then else part will be execute.

Syntax

if [ expression ]
then
   statement1
else
   statement2
fi

if..elif..else..fi statement (Else If ladder) =

To use multiple conditions in one if-else block, then elif keyword is used in shell.

if [ expression1 ]
then
   statement1
   statement2
   .
   .
elif [ expression2 ]
then
   statement3
   statement4
   .
   .
else
   statement5
fi

if..then..else..if..then..fi..fi..(Nested if)

Nested if-else block can be used when, one condition is satisfies then it again checks another condition.

Syntax:

if [ expression1 ]
then
   statement1
   statement2
   .
else
   if [ expression2 ]
   then
      statement3
      .
   fi
fi

switch statement

case statement works as a switch statement if specified value match with the pattern then it will execute a block of that particular pattern When a match is found all of the associated statements until the double semicolon (;;) is executed. A case will be terminated when the last command is executed. If there is no match, the exit status of the case is zero.

Syntax:

case  in
   Pattern 1) Statement 1;;
   Pattern n) Statement n;;
esac

Looping and skipping

For loops allow you to execute statements a specific number of times.

Looping with numbers:

#!/bin/bash

for i in {1..5}
do
    echo $i
done

Looping with strings:

#!/bin/bash

for X in cyan magenta yellow  
do
	echo $X
done

While loop

While loops check for a condition and loop until the condition remains true. We need to provide a counter statement that increments the counter to control loop execution.

#!/bin/bash
i=1
while [[ $i -le 10 ]] ; do
   echo "$i"
  (( i += 1 ))
done

Reading files:

Suppose we have a file sample_file.txt as shown below:

#!/bin/bash

LINE=1

while read -r CURRENT_LINE
	do
		echo "$LINE: $CURRENT_LINE"
    ((LINE++))
done < "sample_file.txt"

How to execute commands with back ticks

If you need to include the output of a complex command in your script, you can write the statement inside back ticks.

syntax:

var= ` commands `

Example: Suppose we want to get the output of a list of mountpoints with tmpfs in their name. We can craft a statement like this: df -h | grep tmpfs.

#!/bin/bash

var=`df -h | grep tmpfs`
echo $var

How to Automate Scripts by Scheduling via cron Jobs

Cron is a job scheduling utility present in Unix like systems. Jobs can be scheduled to execute daily, weekly, monthly or in a specific time of the day. Automation in Linux heavily relies on cron jobs.

Below is the syntax to schedule crons:

# Cron job example
* * * * * sh /path/to/script.sh

Here, * represent represents minute(s) hour(s) day(s) month(s) weekday(s), respectively.

Last modified 2 years ago Last modified on Nov 12, 2022, 8:07:16 PM
Note: See TracWiki for help on using the wiki.