Bash Scripting Session - 2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 52

SESSION 2

BASH SCRIPTING
ESL
Prepared by:
Ali Mohamed
Ali El–Sherbeny
Mahmoud Saad
OUTLINES
■ MOTIVATION (10 MINS)
■ REVIEW ON FIRST SESSION

1. WILD CARDS
2. PIPING
3. SOME COMMANDS
■ NEW COMMANDS(CAT/MORE/LESS/ECHO/READ]
■ USER ADMINISTRATION
OUTLINES

■ QUESTIONS TIME
■ BREAK (15 MINS)
■ FILE PERMISSION
■ CREATE VARIABLES
■ POSITIONAL PARAMETERS
■ FIRST SCRIPT RUN
■ ARITHMETIC& LOGICAL
Review on some commands :
Function command
Know present working directory (where am I) pwd
Change to another place cd
Go to parent directory cd ..
Go to previous directory cd -
Go to relative path cd directory or cd ./directory
Go to home directory cd or cd~
List contents of current directory ls , ls -alh , ls --all
View contents in tree format tree
Get help with the command man , whatis , help
Forgot part of the command man –k part of the command
Move files to new place or rename files mv oldFileName NetFileName
mv FileName NewPlaceOrDirectory
Copy files in same / other directories cp filename NewCopiedFileName
Review

Function command
Remove directories rmdir , rm -r
Create new file touch filename
Create new directory mkdir
Cat command

■ 1)Reads a text file or displays its contents on terminal .


EX : cat filename

2) creates a text file and write in it , or overwrite in existing file


EX : cat > file name
write your txt then press enter then ctrl+c .

3) append text to existing file .


EX : cat >> filename
write your txt then press enter then ctrl+c .
less , more , pg

■ Less filename
more filename
pg filename

view files in form of pages (better view than cat)


use space to view more of the file contents
use "q" or type "q" then enter to quit any of more/less/pg views .
grep

■ Searches for certain sequence of characters in the given file name.

Format : grep SearchPattern FileNameToSearchIn

Some options function


-v Print all lines that don't match the pattern
-n Print matched lines and the line numbers
-c View count of matching lines .
-I Case insesnetive search
Task

■ Since we understood grep , what do these commands do ?

Find
whatis
cut
sort

■ Sorts (arranges) file lines alphabetically / numerically .

Format : sort filename

option Function
-n Numerical sort
-r Reverse sort (descending order)
-f Sort upper and lower case together
-k fieldnuumber Sort according to the field number
specified
wc

■ Count words , bytes , characters , lines in a specific file name .

Format : wc Filename

options Function
-l Count lines
-w Count words
-c Count bytes
-m Count chars
PIPING

■ Output of the first command is the input to second command .

Output of second command is considered filtered output of first command.

| : pipe sign .

Ecamples :

cat filename | less


ls | grep word
ls| sort
ls | grep word | sort
cat filename | sort -k 2 | grep a
REDIRECTION
■ The standard (default) input for the command is the terminal (through the argument you pass
to the command) , and the standard output is also the terminal (the terminal screen).

Redirection is changing the standard input or output to another input or output you specify.

1. OutPut redirection :

Format : command > filename


for appending instead of overwriting : command >> filename
Example : ls > filename
The output of ls will not be displayed on screen , it will be saved to the specified file.
REDIRECTION :
■ 2. Input Redirection :

command < filename


Example : grep pattern < filename

3. Error Redirection :

Format : command 2> filename


Example : lsa 2> filename

Note :
0 represent standard input
1 represent standard output
2 represent standard error
Example :
lsa 2>filename

To Redirect both output and error on same file :


Format : command &> filename
Task

■ Create text file using cat


sort this file taking the text file you created as standard input , another file as standard
output .

Solution :
cat > textfile
sort 0<textfile 1>outputFile
Task

■ Required :

command1 : list contents of pwd in a file called list


command2: count the lines in this text and append the line count to the same text file
instead of showing it on screen .

SOLUTION :
ls –lh > test
wc –l < test 1>>test
Variables :

■ Variables used by shell can be :


1.environment variables .
2.local variables .
Environment variables :

■ - system defined variables .


-available for shell and other processes started by shell .
-some programs need environment variables to start properly .
- some of them are set by user , others set by system others by shell .
Environement variable What it saves
HOME Home directory of current user.
PATH Search path for commands , paths are
separated by ":" , called delimiter .
PWD Current working directory
UID Saves current user id .
USER Saves your user name .
SHELL Saves path to your login shell .
Local variables :
■ - variables used in current shell instance (means they are used in the scope you defined
them in) .
- used by shell but NOT by programs started by shell .

- we use the "$" sign while accessing the variable but we don't use it when we give a value
to this variable .

-values assigned through variables through "read" or you assign a value to them instantly.

Example :

x=5 (no spaces)


echo $x
``

■ If we want to assign the output of a command as a value for the variable we use the ``
quotations .

Example:
set hi hello hey
x = `echo $*`
echo $x
Positional parameters (command line
arguments)
■ - A facility in the shell called positional parameters. Positional parameters are a series
of special variables ($0 through $9) that contain the contents of the command line.
-Arguments passed to a shell script while calling it in the command line are called
positional parameters .
- They can be set by 2 ways :
1. The "set" command
example :
set esl 2018
now $1 saves the word "esl" , $2 saves the word 2018
2. Passing them when calling script :
bash scriptname esl 2018
$1 saves the word "esl" , $2 saves the word 2018 , same as above but they can be used
within the script .
Positional Parameters

■ "shift" command is used to shift positional parameters .


Example:
set esl 2018 2019 2020
shift

Before shift After shift


$1 = esl Old $1 deleted , $1 = 2018
$2 = 2018 $2 = 2019
$3 = 2019 $3 = 2020
Positional Parameters :

Parameter what it saves


$$ Has current shell PID (program ID)
$0 Filename of current script
$1 , $2 , .. Variables passed to script
$# Number of passed variables to script
$* Saves all variables passed to script together
$? Saves exit status .
Exit status :

■ After any command is executed , it returns exit status that shows if this command is
executed suuccesfully or failed while execution .

- It's saves in $? , you can check it to make sure the commands run well .

-
At exit status = 0 Means command run well
At exit status = 1 Means command failed , some commands
return numbers other than 1 to determine
reason of failiure .
Operators :

■ 1. Mathematical operators :

operator meaning
+ add
- subtract
/ division
\* multiply
% Remainder of division
Mathematical Operators :

■ Normally echo reads the inputs as if they're string . Therefore using the rthimitic
operators directly won't work . Therefore we use commands or processes to solve this :

a) expr
Deals with integer arguments , gives integer outputs .
DONOT FORGET SPACES WHILE USING IT .

example:

x=`expr 2 + 2`
exho $x
Continue : MAthematical operators

■ B) variable=$(( operation )) or (( The whole equation ))

Examples :

a=10
c=$(($a+4))
((d=$a+$c))
Continue : Mathematical operators

■ C) bc

Used for floating point operations .


DOOT FORGET THE SPACES .

Examples :
echo 20 + 5 / 2 | bc #must leave spaces to work
echo 'scale=4;20+5/2' |bc #spaces here are fine
Logical operators

■ For numbers :

operator meaning
-eq Equal ?
-ne Not equal ?
-lt Less than ?
-le Less than or equal ?
-gt Greater than ?
-ge Greater than or equal ?
Logical Operators :
■ For strings
Operator Meaning
Str1 == str2 Equal ?
Str1 != str2 Not equal ?
-z str Null string ?
-n str Not null string ?

Null string means its length equals zero .


Example :
a=""
if [ -z "$a" ];
then
echo it's a null string ;
fi
Boolean operators :
expression meaning
-a and
-o or
Administrating users and groups:
■  Management of users and groups accounts is an important task for all system
■ admins.
■  You can manage this process from GUI or from terminal.
■  Configuration files related to this task:
■ – /etc/passwd
■ – /etc/shadow -> has the encrypted password for each user.
■ – /etc/group
■  Useful commands
■ – id
■ • Displays effective user id, user name, group id, group name.
■ – whoami
■ • Displays the current effective user
■ – su [–] [username]
■ • Switch between user accounts
WILD CARDS
$ touch A.log a_12.log .log
$ touch A7_.html & B&G.html & .htm
$ touch 111.log 155.log 199.log
$ touch ESL-2016 ESL-2017 ESL-2018
$ rm *.log
$ rm *.*htm*
$ rm 1??.log
$ ls –l ESL-201[678].log
■ 1) asterisk (*) ■ 2) Question mark (?)
>The * can replace any set of characters > The ? represents or matches a single
including (none) in the file/directory name occurrence of any character excluding the none
character
EX
EX
$ rm *.log
$ rm 1??.log
>> all log files in the given directory is
>> (100.log & 199.log ) files is deleted so
deleted through is command we can delete more than
(A.log & a_12.log & .log) is deleted 99 files

$ rm *.*htm* ■ 3) Bracketed characters ([ ])

>>by this command any file start with any > matches any occurrence of character
set of arbitary characters then followed by enclosed in the square brackets
. Then followed by any set of $ls –l ESL-201[678].log
arbitary characters then followed by htm
List all file named >>
then followed by any arbitary set of
characters (ESL-2016 & ESL-2017 & ESL-2018)
(A7_.html & B&G.html & .htm ) is >> $ ls ESL-201[6-8].log
deleted Is this command the same as above? [just try]
FILE PERMISSIONS
$ls –l (list using long format)
1) File type

- (File) d(directory)

2)permission

r: read >>in case of file reading the file is permitted


>>in case of directory listing the directory is permitted

w: write >>in case of file editing in the file is permitted


>>in case of directory adding directories inside the directory is permitted

x:Execute >>in case of file exectuing in the file is permitted


>>in case of directory it has meaningless
permission is broken into 3 sections

- user permissions - group permissions - others permissions


NEW COMMANDS
>> "echo" Command

This command used to print/display it's argument on the


screen

$echo " ESL_2018" = $ echo ESL_2018


>>"read" Command

This command used to read the user input from the keyboard

___If you won’t specify the variable where to store the data.
By default the data is stored in the variable called REPLY. So we can invoke the data
as $REPLY

EX $ read [try to print the value of REPLAY variable]

__If you specify a variable so The variable become place holder for the text you enter.
The whole unit of text is stored in the variable you provide

EX & read name [try to print the value of name variable]


READ COMMAND USING OPTIONS

1)$read –s
This option -s means secret or secure whatever is used to read the sensitive data like passwords.
Generally when you type entering the data it appears in the terminal. But with this option is used
the text won’t appear in terminal

2)$read –n
This option -n allows the user to enter only the specific length of characters. It won't allow you
to enter more than the given number. After reaching the length you have given it automatically
ends the reading mode. You again no need to press the Enter key

3)$read -p “prompt(hint)_text”
Here the user read the data along with some hint text . The hint text helps the user what he/she
has to enter.(-p here stands for the prompt).
Ex: read –p "Enter Your Name:" name
if name variable not existed so the user input is stored in REPLAY variable

4)$read -t 10 –p "Your name" user


here if no input provided within 10 seconds so program will be aborted
Question Time !!
Q1

What is the command used to search


for pattern of characters in file names

???
Q2

What is the command used to


print the working directory

???
Q3

What is the command used to


get help with commands

???
FIRST SCRIPT RUN
Editors
1)GUI based Editors
- gedit

2)Terminal based Editors


- nano (simplest terminal-based editor)
- vi/vim(more powerful but complex)
Using nano editor

To create and open a file using nano editor in one


command

$nano scrpit.sh

To create and open a file using nano editor in two commands

$touch script.sh
$nano scrpit.sh
First Script

#!/bin/bash

$echo "what is your name?" { print on the screen}


$read person { take input from the user}
$echo "Hello $person \n" {print the value of the variable person}

Remove $ >>>> what is the output ?!!!


Run the script
In the terminal write the following commands:-
$chmod +x script_name
$./script_name or $path to script

+ : add permission
- : remove permission
w: Write
r: Read
x: Execute

You might also like