SHELL SCRIPTING EXAMPLE SET 2

 

In "SHELL SCRIPTING EXAMPLE SET 2", You can learn How to declare a static array, How to print all elements of an array, How to print the first element, How to print a particular element, How to print elements in the range, How to extract the length of a particular element, and size of an array, How to replacing sub string temporary. topics with examples.

In "SHELL SCRIPTING EXAMPLE SET 2", You can learn Comparison operators used in Numbers, Strings, and Files.

In this “Shell Script Example Set 1″ article, You can learn different programming commands in LINUX Shell. It covers File related scripts, date-related scripts, calculator related scripts, directory related scripts. Check once.

Shell Scripting Example Set 2

ARRAY IN SHELL

#! /bin/bash
#To declare static Array
arr=(prakhar ankit 1 rishabh manish abhinav)

#To print all elements of array
echo ${arr[@]} # prakhar ankit 1 rishabh manish abhinav
echo ${arr[]} # prakhar ankit 1 rishabh manish abhinav

echo ${arr[@]:0} # prakhar ankit 1 rishabh manish abhinav

echo ${arr[*]:0} # prakhar ankit 1 rishabh manish abhinav

To print first element
echo ${arr[0]} # prakhar
echo ${arr} # prakhar

#To print particular element
echo ${arr[3]} # rishabh
echo ${arr[1]} # ankit

#To print elements in range
echo ${arr[@]:1:4} # ankit 1 rishabh manish
echo ${arr[@]:2:3} # 1 rishabh manish
echo ${arr[0]:1:3} # rak

#Length of a particular element
echo ${#arr[0]} # 7
echo ${#arr} # 7

#Size of an Array
echo ${#arr[@]} #6
echo ${#arr[*]} #6

# Search in Array
echo $(arr[@] /[aA]/) # 1

# Replacing substring Temporary
echo ${arr[@]//a/A} # prAkhAr Ankit 1 rishAbh mAnish AbhinAv
echo ${arr[@]} # prakhar ankit 1 rishabh manish abhinav
echo ${arr[0]//r/R} # pRakhaR ankit 1 Rishabh manish abhinav

Given below table helps you to operate array related queries.

SyntaxResult
arr=()Create an empty array
arr=(1 2 3)Initialize array
${arr[2]}Retrieve third element
${arr[@]}Retrieve all elements
${!arr[@]}Retrieve array indices
${#arr[@]}Calculate array size
arr[0]=3Overwrite 1st element
arr+=(4)Append value(s)
str=$(ls)Save ls output as a string
arr=( $(ls) )Save ls output as an array of files
${arr[@]:s:n}Retrieve n elements starting at index s
array operations in bash shell

From the beginning, Shell Scripting Commands are given below, it helps you to get accurate knowledge in Shell Programming.

1> To show valid login shells.

cat /etc/shells

Output:
#/etc/shells: valid login shells
/bin/sh
/bin/bash
/usr/bin/bash
/bin/rbash

2> How to display which bash you are using?

which bash
Output:
/usr/bin/bash

3> What is the function of Touch command?

Using Touch command, you can create a file i.e. "Touch FileName.sh".

4> How to show file permissions?

ls -al
Output:
-rw-r--r-- 1 saif saif 0 Dec 25 18:52 hello.sh

5> Write a program in Shell to print "Hello World".

#!/bin/bash/
echo "Hello World"
Output
Hello World

6> Write a program to declare a variable and print it.

var=100
namevar=Saif
echo var= $var
echo Name= $namevar
Output:
var= 100
Name= Saif

7> Write a program to read user input.

Type 1:

#!bin/bash
echo "Enter name1: "
read name1
echo "Enter name2: "
read name2
echo "Enter name3: "
read name3
echo "Entered name: $name1 $name2 $name3 "

Output:
Enter name1:
Sk
Enter name2:
Saif
Enter name3:
Uddin
Entered name: Sk Saif Uddin

TYPE 2:

#!bin/bash
read -p 'username: ' user_var
read -sp 'password: ' pass_var
echo "Username: $user_var"
echo "password: $pass_var"

Output:
username: Saif
password:
username: Saif
password: abc

TYPE 3:

echo "Enter names: "
read -a names
echo "Names: ${names[0]}, ${names[1]} "

Output
Enter Names:
abcd efg
Names: abcd, efg

TYPE 4:

echo "Enter name: "
read
echo "Name is $REPLY"

Output:
Enter name: Saif
Name is Saif

8> Write a program to pass argument to a bash-script.

echo $1 $2 $3 ' > echo $1 $2 $3'
echo $0 $1 $2 $3 ' > echo $0 $1 $2 $3'

Output: Terminal> sh passarg1.sh H B O
H B O > echo $1 $2 $3
passarg1.sh H B O > echo $0 $1 $2 $3

9> Write a program to print Shell name, Shell version, Home directory and Current working directory.

echo Our shell name is $BASH
echo Our shell version is $BASH_VERSION
echo Our home directory is $HOME
echo Our current working directory is $PWD

Output:
Our shell name is /usr/bin/bash
Our shell version is 5.1.0(1)-rc3
Our home directory is /home/saif
Our current working directory is /home/saif/Shell/

This script is running by changing the mode of the file. The command "chmod +x filename.sh" is used to change a read-only file into an executable file. This executable file is run using "./filename.sh". Sometimes, Some bash commands are not running in those cases, You can go with change mode and run as ./filename.sh. From now, All given below programs are done in the same pattern.

Compare Numbers in Linux Shell Script

This is one the most common evaluation method i.e. comparing two or more numbers. We will now create a script for doing numeric comparison, but before we do that we need to know the parameters that are used to compare numerical values . Below mentioned is the list of parameters used for numeric comparisons

  1. num1 -eq num2                  check if 1st  number is equal to 2nd number
  2. num1 -ge num2                  checks if 1st  number  is greater than or equal to 2nd number
  3. num1 -gt num2                  checks if 1st  number is greater than 2nd number
  4. num1 -le num2                   checks if 1st number is less than or equal to 2nd number
  5. num1 -lt num2                   checks if 1st  number  is less than 2nd number
  6. num1 -ne num2                  checks if 1st  number  is not equal to 2nd number

Compare Strings in Linux Shell Script

When creating a bash script, we might also be required to compare two or more strings & comparing strings can be a little tricky. For doing strings comparisons, parameters used are

  1. var1 = var2     checks if var1 is the same as string var2
  2. var1 != var2    checks if var1 is not the same as var2
  3. var1 < var2     checks if var1 is less than var2
  4. var1 > var2     checks if var1 is greater than var2
  5. -n var1             checks if var1 has a length greater than zero
  6. -z var1             checks if var1 has a length of zero

You might have noticed that greater than symbol (>) & less than symbol (<) used here are also used for redirection for stdin or stdout in Linux. This can be a problem when these symbols are used in our scripts, so what can be done to address this issue.

Solution is simple , when using any of these symbols in scripts, they should be used with escape character i.e. use it as “/>” or “/<“.

File comparison in Linux Shell Script

This might be the most important function of comparison & is probably the most used than any other comparison. The Parameters that are used for file comparison are

  1. -d file                        checks if the file exists and is it’s a directory
  2. -e file                        checks if the file exists on the system
  3. -w file                       checks if the file exists on the system and if it is writable
  4. -r file                        checks if the file exists on the system and it is readable
  5. -s file                        checks if the file exists on the system and it is not empty
  6. -f file                         checks if the file exists on the system and it is a file
  7. -O file                       checks if the file exists on the system and if it’s is owned by the current user
  8. -G file                        checks if the file exists and the default group is the same as the current user
  9. -x file                         checks if the file exists on the system and is executable
  10. file A -nt file B         checks if file A is newer than file B
  11. file A -ot file B          checks if file A is older than file B

Now let’s create a script doing the string comparisons and number comparisons.

#!/bin/bash

count=10
word=abc

#If statement for Number comparison

if [ $count -eq 10 ]
then
echo "Condition is true for number"
fi

#If statement for String comparison

if [ $word == "abc" ]
then
echo "Condition is true for string"
fi

#If-Else statement for Character comparison

#Double SQUARE BRACKETS

word=a
if [[ $word < "b" ]]
then
echo "Condition is true for word"
else
echo "Condition is false for word"
fi

#If-Elif-Else statement for Number comparison

pass=223
if [ pass == 222 ]
then
echo "Password is 222"
elif [[ pass -eq 223 ]]
then
echo "Password is 223"
else
echo "Password not matched"
fi

Output:
Condition is true for number
Condition is true for string
Condition is true for word
Password is 223


In "SHELL SCRIPTING EXAMPLE SET 2", You can learn How to declare a static array, How to print all elements of an array, How to print the first element, How to print a particular element, How to print elements in the range, How to extract the length of a particular element, and size of an array, How to replacing substring temporary. topics with examples. You can also learn Comparison operators used in Numbers, Strings, and Files.

Comments

Popular posts from this blog

PROCESS SCHEDULING ALGORITHMS

SCHEDULING AND SCHEDULERS

Shell Script Example Set 1