56
Linux Bash Shell script 01/16/2022 Linux Bash Shell script 1

Bash Shell Scripting

Embed Size (px)

DESCRIPTION

Syntax, Control Statements, Regular expressions in bash

Citation preview

Page 1: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 1

Linux Bash Shell script

Page 2: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 2

• A script is a list of system commands stored in a file.

• Steps to write a script :-

• Use any editor like vi or vim

• chmod permission your-script-name.

• Examples:-•

$ chmod +x <filename.sh>•

$ chmod 755 <filename.sh>

• Execute your script as:

• $ bash filename.sh• $ bash fileneme.sh• $ ./filename.sh

Page 3: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 3

• My first shell script

clear• echo “hello world“

• $ ./first

• $ chmod 755 first

• $ ./first

• Variables in Shell:

• In Linux (Shell), there are two types of variable:

• (1) System variables :

• (2) User defined variables :

Page 4: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 4

• $ echo $USERNAME

• $ echo $HOME

• User defined variables :

• variable name=value

• Examples:

• $x = 10

• echo Command:

• echo command to display text

Page 5: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 5

Shell Arithmetic

• arithmetic operations

• Syntax:

expr op1 math-operator op2

Examples:

$ expr 10 + 30

$ expr 20 – 10

$ expr 100 / 20

$ expr 200 % 30

$ expr 100 \* 30

$ echo `expr 60 + 30`

Page 6: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 6

Renaming filesmv test1 test2

Deleting filesrm -i test1

Creating directoriesmkdir dir3

Deleting directoriesrmdir dir3

Page 7: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 7

processes

• $ ps PID TTY TIME CMD

• $ ps -efUID PID PPID C STIME TTY TIME CMD

• $ ps -lF S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME

CMD

• $ ps -efHUID PID PPID C STIME TTY TIME CMD

Page 8: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 8

Creating files:

$ touch test1$ ls -il test1

Copying files:

cp source destinationcp test1 test2

Linking files:

There are two different types of file links in Linux:

a. A symbolic, or soft, linkb. A hard link

Page 9: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 9

Quotes

" Double Quotes

Double Quotes" - Anything enclose in double quotes removed meaning of that characters (except \ and $).

' Single quotes 'Single quotes' - Enclosed in single quotes remains unchanged.

` Back quote `Back quote` - To execute command

Page 10: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 10

• Pipes:

who | wc –l

Reading from Files:

$ read message $ echo $message

Read command to read lines from files

• Command substitution:

Var=`date` Var=$(date)

• Background Processes:

• ls -R /tmp &

Page 11: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 11

Reading with While

while read ip name alias do if [ ! -z “$name” ]; then # Use echo -en here to suppress ending the line; # aliases may still be added echo -en “IP is $ip - its name is $name”if [ ! -z “$aliases” ]; then echo “ Aliases: $aliases” else # Just echo a blank line echo fi fi done < /etc/hosts

Page 12: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 12

Stopping processeskill piddisk space$ df$ df –hDisk usages:$ du

Commands:$ cat file1$ sort file1$ cat file2$ sort file2$ sort -n file2

Page 13: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 13

Searching for data

• grep [options] pattern [file]

• The grep command searches either the input or the file you specify for lines that contain characters that match the specified pattern. The output from grep is the lines that contain the matching pattern.

Page 14: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 14

RANDOM produces a random number between 0 and 32767. This simple recipe produces 10 random

numbers between 200 and 500:

$ cat random.sh#!/bin/bashMIN=200MAX=500let “scope = $MAX - $MIN”if [ “$scope” -le “0” ]; thenecho “Error - MAX is less than MIN!”fifor i in `seq 1 10`dolet result=”$RANDOM % $scope + $MIN”echo “A random number between $MIN and $MAX is $result”Done

$ ./random.sh

Page 15: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 15

Problem 1: Code to calculate the length of the hypotenuse of a Pythagorean triangle

$ cat hypotenuse.sh#!/bin/sh# calculate the length of the hypotenuse of a Pythagorean

triangle# using hypotenuse^2 = adjacent^2 + opposite^2echo -n “Enter the Adjacent length: “read adjacentecho -n “Enter the Opposite length: “read oppositeosquared=$(($opposite ** 2)) # get o^2asquared=$(($adjacent ** 2)) # get a^2hsquared=$(($osquered + $asquared)) # h^2 = a^2 + o^2hypotenuse=`echo “scale=3;sqrt ($hsquared)” | bc`# bc does sqrtecho “The Hypotenuse is $hypotenuse”

Page 16: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 16

Environment Variables

• There are two types of environment variables in the bash shell

• Global variables• Local variables

Page 17: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 17

Variable Arrays

• An array is a variable that can hold multiple values.

• To set multiple values for an environment variable, just list them in parentheses, with each value

• separated by a space:• $ mytest=(one two three four five)• $• Not much excitement there. If you try to display the array

as a normal environment variable,• you’ll be disappointed:• $ echo $mytest• one• $• Only the first value in the array appears. To reference an

individual array element, you must use• a numerical index value, which represents its place in the

array. The numeric value is enclosed in• square brackets:• $ echo ${mytest[2]}• three• $

Page 18: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 18

Scripting basics

$ date ; who

$ chmod u+x test1

$ ./test1

$ echo This is a test

This is a test

$ echo Let’s see if this’ll workLets see if thisll work$

Page 19: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 19

The backtick

One of the most useful features of shell scripts is the lowly back quote character, usually called the

backtick (`) in the Linux world.

You must surround the entire command line command with backtick characters:

testing=`date`

$ cat test5#!/bin/bash# using the backtick charactertesting=`date`echo "The date and time are: " $testing$

Page 20: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 20

Redirecting Input and Output

• Output redirection

The most basic type of redirection is sending output from a command to a file. The bash shell uses the greater-than symbol for this:

command > outputfile

Input redirection

Input redirection is the opposite of output redirection

The input redirection symbol is the less-than symbol (<):

command < inputfile

Page 21: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 21

The expr command

$ expr 1 + 56The bash shell includes the expr command to stay compatible

with the Bourne shell; however, italso provides a much easier way of performing mathematical

equations

$ var1=$[1 + 5]$ echo $var16$ var2 = $[$var1 * 2]$ echo $var212$

Page 22: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 22

$ chmod u+x test7$ ./test7The final result is 500$

Using bc in scriptsvariable=`echo "options; expression" | bc`

$ chmod u+x test9$ ./test9The answer is .6880$

$ cat test10#!/bin/bashvar1=100

Page 23: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 23

var2=45var3=`echo "scale=4; $var1 / $var2" | bc`echo The answer for this is $var3$

$ cat test11#!/bin/bashvar1=20var2=3.14159var3=`echo "scale=4; $var1 * $var1" | bc`var4=`echo "scale=4; $var3 * $var2" | bc`echo The final result is $var4$

Page 24: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 24

$ cat test12#!/bin/bashvar1=10.46var2=43.67var3=33.2var4=71var5=`bc << EOFscale = 4a1 = ( $var1 * $var2)b1 = ($var3 * $var4)a1 + b1EOF`echo The final answer for this mess is $var5

• $

Page 25: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 25

Checking the exit status

$ dateSat Sep 29 10:01:30 EDT 2007$ echo $?0$

$ cat test13#!/bin/bash# testing the exit statusvar1=10var2=30var3=$[ $var1 + var2 ]echo The answer is $var3exit 5$

Page 26: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 26

$ cat test14#!/bin/bash# testing the exit statusvar1=10var2=30var3=$[ $var1 + var2 ]exit $var3$

$ chmod u+x test14$ ./test14

$ echo $?40$

Page 27: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 27

Structured Commands

• if-then Statement:

The if-then statement has the following format:

if commandthencommandsFi

The if-then-else Statement

if commandthencommandselsecommandsfi

Page 28: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 28

Nesting ifs

if command1thencommandselif command2thenmore commandsFi

• You can continue to string elif statements together, creating one huge if-then-elif conglomeration:

if command1thencommand set 1elif command2thencommand set 2elif command3thencommand set 3elif command4thencommand set 4fi

Page 29: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 29

Numeric comparisons

• The most common method for using the test command is to perform a comparison of two numeric values.

#!/bin/bash# using numeric test comparisonsval1=10val2=11if [ $val1 -gt 5 ]thenecho "The test value $val1 is greater than 5"fiif [ $val1 -eq $val2 ]thenecho "The values are equal"elseecho "The values are different"fi

Page 30: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 30

Comparison Description

n1 -eq n2 Check if n1 is equal to n2.

n1 -ge n2 Check if n1 is greater than or equal to n2.

n1 -gt n2 Check if n1 is greater than n2.

n1 -le n2 Check if n1 is less than or equal to n2.

n1 -lt n2 Check if n1 is less than n2.

Page 31: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 31

String comparisons

• String equality• The equal and not equal conditions are fairly self-

explanatory with strings. It’s pretty easy to know

• when two string values are the same or not:

#!/bin/bash# testing string equalitytestuser=richif [ $USER = $testuser ]thenecho "Welcome $testuser"fi$ ./test7Welcome rich$

Page 32: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 32

The test Command String Comparisons

Comparison Description

str1 = str2 Check if str1 is the same as string str2.

str1 != str2 Check if str1 is not the same as str2.

str1 < str2 Check if str1 is less than str2.

str1 > str2 Check if str1 is greater than str2.

Page 33: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 33

The for Command

for var in listdocommandsDone

Reading values in a list

#!/bin/bash# basic for commandfor test in Alabama Alaska Arizona Arkansas California Coloradodoecho The next state is $testdone$ ./test1

Page 34: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 34

reading values from a file

file="states"for state in `cat $file`doecho "Visit beautiful $state"Done

Page 35: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 35

internal field separator

A space A tab A newline

file="states"IFS=$’\n’for state in `cat $file`doecho "Visit beautiful $state"Done

Page 36: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 36

Reading a directory using wildcards

for file in /home/tmp/*doif [ -d "$file" ]thenecho "$file is a directory"elif [ -f "$file" ]Thenecho "$file is a file"fiDone

Page 37: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 37

For loop

for (( i=1; i ‹= 10; i++ ))doecho "The next number is $i"done

Page 38: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 38

Multi.sh

#!/bin/sha=$1if [ $a -lt 1 -o $a -gt 9 ]; thenecho “The number is out of range [1,9]”exitfiecho "Multiplication Table for $a"for i in 1 2 3 4 5 6 7 8 9dom=$[a * i]echo "$a x $i = $m"done

Page 39: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 39

Shell Arguments

#!/bin/shecho "Total number of arguments = $#"echo "Shell script name = $0"echo "First arguemnt = $1"echo "Second arguemnt = $2"echo “Third argument = $3”echo "All arguments (a word) = $*"echo "All arguments in array = $@"

Page 40: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 40

Loops

#!/bin/shfor i in 1 2 3 4 5 6 7 8 9doecho “number $i”done

#!/bin/shfor i in `seq 1 100`doif [ $i -lt 5 ]; thencontinueelif [ $i -gt 10 ]; thenbreakfiecho "number $i"done

Page 41: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 41

Loops (while statement)

whileexpression   dostatementsdone

#!/bin/shi=1sum=0while [ $i -le 10 ]dosum=$[sum + i]echo "$i sum = $sum"i=$[i+1]done

Page 42: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 42

multiple variables

for (( a=1, b=10; a ‹= 10; a++, b-- ))doecho "$a - $b"Done

Nesting Loops:

for (( a = 1; a ‹= 3; a++ ))doecho "Starting loop $a:"for (( b = 1; b ‹= 3; b++ ))doecho " Inside loop: $b"donedone

Page 43: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 43

functions

• #!/bin/sh• function tm_score () {• local pdb1=$1• local pdb2=$2• echo "`tmscore $pdb1 $pdb2 | grep ^TM | awk '{print

$3}'`"• }• a=$1• b=$2• tm_score $a $b

Page 44: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 44

Breaking out of an inner loop

for (( a = 1; a ‹ 4; a++ ))doecho "Outer loop: $a"for (( b = 1; b ‹ 100; b++ ))doif [ $b -eq 5 ]thenbreakfiecho " Inner loop: $b"donedone

Page 45: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 45

Breaking out of an outer loop

for (( a = 1; a ‹ 4; a++ ))doecho "Outer loop: $a"for (( b = 1; b ‹ 100; b++ ))doif [ $b -gt 4 ]thenbreak 2fiecho " Inner loop: $b"donedone

Page 46: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 46

The continue command

for (( var1 = 1; var1 ‹ 15; var1++ ))doif [ $var1 -gt 5 ] && [ $var1 -lt 10 ]thencontinuefiecho "Iteration number: $var1"done

Page 47: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 47

Continue

for (( a = 1; a ‹= 5; a++ ))doecho "Iteration $a:"for (( b = 1; b ‹ 3; b++ ))doif [ $a -gt 2 ] && [ $a -lt 4 ]thencontinue 2fivar3=$[ $a * $b ]echo " The result of $a * $b is $var3"donedone

Page 48: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 48

Read file into bash array

– exec < $1let count=0

while read LINE; do

ARRAY[$count]=$LINE((count++))done

echo Number of elements: ${#ARRAY[@]}# echo array's contentecho ${ARRAY[@]}# restore stdin from filedescriptor 10# and close filedescriptor 10exec 0<&10 10<&-

Page 49: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 49

Processing the Output of a Loop

for file in /home/rich/*doif [ -d "$file" ]thenecho "$file is a directory"elifecho "$file is a file"fidone > output.txt

Page 50: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 50

Creating a functionfunction name {commands}

name() {commands}

Page 51: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 51

Using functions

function func1 {echo "This is an example of a function"}count=1while [ $count -le 5 ]dofunc1count=$[ $count + 1 ]done

Page 52: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 52

count=1echo "This line comes before the function

definition"function func1 {echo "This is an example of a function"}while [ $count -le 5 ]dofunc1count=$[ $count + 1 ]doneecho "This is the end of the loop"func2echo "Now this is the end of the script"function func2 {echo "This is an example of a function"}

Page 53: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 53

Regex

• $echo {a..z}• $ echo {5..-1}

• if [[ $digit =~ [0-9] ]]; then echo '$digit is a digit' else echo "oops" fi

Page 54: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 54

Regular expression operators

Operator

. Matches any single character.

? The preceding item is optional and will be matched, at most, once.

* The preceding item will be matched zero or more times.

+ The preceding item will be matched one or more times.

{N} The preceding item is matched exactly N times.

{N,} The preceding item is matched N or more times.

{N,M} The preceding item is matched at least N times, but not more than M times.

Page 55: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 55

Regular expressions

As with other comparison operators (e.g., -lt or ==), bash will return a zero if an expression like $digit =~ "[[0-9]]" shows that the variable on the left matches the expression on the right and a one otherwise. This example test asks whether the value of $digit matches a single digit.

if [[ $digit =~ [0-9] ]]; then echo '$digit is a digit'else echo "oops"fi

You can also check whether a reply to a prompt is numeric with similar syntax:

echo -n "Your answer> "read REPLYif [[ $REPLY =~ ^[0-9]+$ ]]; then echo Numericelse echo Non-numericfi

Page 56: Bash Shell Scripting

04/12/2023 Linux Bash Shell script 56

Sample bash script to perform the unpack/compile process

#!/usr/bin/env bash

if [ -d work ]then# remove old work directory if it exists rm -rf workfimkdir workcd worktar xzf /usr/src/distfiles/sed-3.02.tar.gzcd sed-3.02./configure --prefix=/usrmake