Shell Scripting by Santosh
Shell Scripting by Santosh
Presentation by V.SANTOSH
Agenda
We need to know the vi editor before we learn shell scripting. Use vi editor to:
create text files edit text files
Vi Editor
Vi is a powerful editor Vi stands for visual editor
3 modes in vi
1. Command mode (Default mode) 2. Insert mode = to Insert Text 3. Ex mode = To save to save and quit quit without saving etc.
Command mode in vi
Command mode is the default mode in vi The moment you open the file with vi <filename> , you are in command mode In command mode is for : i. Cursor movement ii. Copy iii. Paste (yank) iv. Cut or delete v. Go to etc.
6
Cursor movement in vi
Cursor movement is possible only in command
mode in vi Arrow keys may work Standard keys for cursor movement are: i. h - for left ii. l - for right iii. j - for down iv. k - for up
7
10
11
12
13
Insert Mode
Insert Mode = to insert the text Press <insert> key to enter insert mode after which you can type the text. a = append after cursor A = Append after line I = insert before cursor I = Insert before line o = opens a new line O = opens new line above
14
15
16
Search/Replace in vi editor
Search/Replace as in sed Affects current line by default Use m,n ranges (where m is first line and n is the last line in the range) or % for whole file :1,10s/find string/replace with string/g :%s/find string/replace with string/gi s = search, g=more than one instance per line , i = case insensitive
17
Ex mode
:q <enter> to exit, if no changes are made to the file :q! <enter> to quit forcibly abandoning changes :wq <enter> to save and Exit :x <enter> same as above ZZ to save and Exit (uppercase)
18
Configuring vi
Few configuration options : :set number :set autoindent :set textwidth=65 (vim only) :set showmatch :set ignorecase
19
20
Types of variables
Shell Variables or Local variables Shell variables or local variables exist only in the current shell instance. Environmental variables or global variables. These variables can be passed on to the subshells by exporting the variables.
21
System Variables
System Variable Purpose BASH=/bin/bash shell name BASH_VERSION=1.14.7(1) shell version name COLUMNS=80 No. of columns for our screen HOME=/home/student Our home directory LINES=25 No. of columns for our screen LOGNAME=student login name OSTYPE=Linux Our Os type
22
24
Types of varaiables
User defined variables = variables defined by the user. Is case sensitive, can be defined in any case. Ex: #c=6 # echo $c 6 System defined variables =Defined by the system used to configure the shell environment System defined variables are in upper case
25
26
27
29
UDV and System Variable) (1) Variable name must begin with Alphanumeric character or underscore character (_), followed by one or more Alphanumeric character. For e.g. Valid shell variable are as follows HOME SYSTEM_VERSION
30
31
Exit Status
used to check whether command or shell script executed is successful or not. (1) If return value is zero (0), command is successful. (2) If return value is nonzero, command is not successful or some sort of error executing command/shell script. This value is know as Exit Status. echo $? Displays the exit status.
34
SHELL SCRIPTING
Shell scripts are like batch files Shell scripts are used to : automate the tasks. for repetitive tasks Customising the work environment Executing various administrative tasks
35
36
37
Shell keywords
echo = for output prints whatever is mentioned after that word on the screen ( can be redirected) Ex: echo hello = displays hello read = for input Ex: read name takes input from keyboard and stores the value in the variable name. (other keywords will be discussed throughout This presentation)
38
Shell Keywords
echo read if fi else set do case shift esac export break then continue for exit while return until unset readonly umask eval
39
Handling Output
echo = Used to display on the screen Ex: echo hello world
40
Handling Input
read <Variable> = to take input from keyboard and store the value in the variable Ex: The following script takes the name as input from keyboard and displays the name and welcome statement # vi inout.sh echo n enter your name: read name echo $name,welcome to the Shell Scripting class
41
Assignment 2
Write a program to input 2 nos., Calculate and print the following : 1. Sum 2. Difference 3. Product 4. Quotient 5. Remainder
44
45
Positional Parameters
Positional parameters is a convenient way to pass data to a program. can be considered as variables defined by the shell. These are named $1 to $9 While $0 indicates the program name.
46
47
Assignment 3
Write a program to pass values to a program from command line and perform the following: Input studentname marks in 5 subjects , Calculate and print the following: Studentname Phy Chem Maths Eng Hin (Marks) Total marks and average marks
48
51
52
Sequential Structure
In Sequential structure, commands are executed in sequence one after the other. Ex: All the shell scripts we discussed so far are sequential structures.
53
Conditional Structures
In conditional structures, Commands are executed based on a condition. Similar to conditional control structures in programming languages, there are some differences. 1. The if condition tests the success of a Linux command, not an expression. 2. The end of an if-then command must be indicated with the keyword fi, and 3. the end of a case command is indicated with the keyword esac.
54
Assignment 4
1) Write a shell script to input 2 nos. and print whether they are equal or not. If not Equal, print the greatest of the 2 nos. 2) Write a shell script to input 2 strings and display whether they are equal or not.
56
57
Syntax of case
Syntax : Case choice in 1) command ;; 2) command;; 3) Command;; *) echo invalid entry;; Esac Note: 1) * indicates a value other those mentioned in the menu. 2) every option is terminated with ;;
58
Repetitive Structures
In repetitive structures, commands are executed repetitively in a loop Ex: 1) for Loop 2) while Loop 3) until Loop
59
Syntax of
Syntax: for variable in list of values do statement done Ex: for i in 1 2 3 4 5 do echo $i done Output : 1 2 3 4 5
for loop
60
Assignment 5
1) Write a shell script to print the nos. from 1 to 10 and their squares using for. 2) Write a shell script to print the even and odd nos. from 1 to 10 using for
64
65
66
Assignment 6
1. Write a program to print the following Patterns : i) 12345 ii) * 1234 ** 123 *** 12 **** 1 *****
67
While Loop
The commands within a while loop are executed repetitively as long as the condition is true. Syntax : while [ condition] do Command 1 Command 2 done
68
71
Until Loop
The commands within an until loop are executed repetitively as long as the condition is false. Syntax : until [ condition] do Command 1 Command 2 done
72
Assignment 7
Write a program to print the even and odd nos. between 1 and 10 using while and until
74
Assignment 8
Write a shell script to print the nos. from 1 to 10 in reverse order using until.
75
76
Functions syntax
Declaring the Function : Function Name () { Command 1 Command 2 } Calling the Function : Function Name
77
Assignment 9
Write a shell script using functions and passing arguments to functions for : 1. Copy 2 files 2. Move a file or rename filea to fileb
81
Getopts
This command is used to check valid command line argument are passed to script. Usually used in while loop. Syntax: getopts {optstring} {variable1} getopts is used by shell to parse command line argument.
82
Getopts continued
"optstring contains the option letters to be recognized; if a letter is followed by a colon, the option is expected to have an argument, which should be separated from it by white space. Each time it is invoked, getopts places the next option in the shell variable variable1, When an option requires an argument,
83
Getopts continued
getopts places that argument into the variable OPTARG. On errors getopts diagnostic messages are printed when illegal options or missing option arguments are encountered. If an illegal option is seen
84
Example of getopts
Consider a script : System details Sys -d -c -os -h Options: Optional arguments -d date -c calendar -os Operating system -h hostname -d demo values (if any of the above options are used their values are not taken)
85
getopts example
echo "Usage: Scriptname -n -a -s -w d echo -d date echo -c calendar echo -os Operating system echo -h hostname echo " x if any of the above options are used "
86
87