1.14k likes | 1.18k Views
Unit -3 Shell Programming. Common Shells. Sh (1971) – Developed by Ken Thompson - Introduced the concept of pipes, filters and redirection Lacked the ability to script. Bourne (1977) – Developed by Stephen Bourne
E N D
Common Shells • Sh(1971) – Developed by Ken Thompson - Introduced the concept of pipes, filters and redirection Lacked the ability to script. • Bourne (1977) – Developed by Stephen Bourne - Introduced the concepts of scripting, control flows, string literals and command substitution - Lacked the ability to define functions • Korn (1978) – Developed by David Korn - Includes features from other shells - Includes advanced features from Ruby and Python languages like - Floating point arithmetic and arrays - File name completion - History feature
Common Shells • C (1978) – Developed by Bill Joy (also called csh) - Provides C language feel - Advanced feature is Command history • Tenex C (1983) – Developed by Ken Greer (also called tcsh) - Command line editing feature - Command completion • Bourne Again Shell – Developed by Brijan Fox (also called bash) - It combines the features of Korn and C shells - Introduced some environment variables - Default shell in Linux. - specific shell variables. - some built-in commands like set and man.
Know about the shells The file /etc/shells lists the shells available under Linux. • It contains a list of all the installed shells, available to all users • The first entry acts as the default shell Note : that each shell does the same job, but each understand a different command syntax and provides different built-in functions.
Shell Scripts Bash .bash_profile: Login initialization file .bashrc: BASH shell configuration file .bash_logout: Logout script Tcsh .login: Login Initialization File .tcshrc: TCSH shell configuration file .logout: Logout file Login/Logout Scripts .cshrc.login (executed only at login) .logout (executed only at logout) Csh
Shell: Responsibilities • Command Interpretation • Providing a scripting language • A process that provides runtime environment
Simple architecture of a Shell User Lexical Analysis Expansion Execution Kernel
Interpretation cycle for shell commands The Shell • Issues the prompt and waits for a command to be entered • Analyses the input and parses it • Scans the command line for meta-characters and performs expansions to give a simple command • Passes command line to the kernel for execution • Waits for command to execute • On completion gives the prompt again; and the cycle continues
Shell: Variables • Control the environment provided by the shell • Set via any of the following activities • After user logs in through login scripts • As a result of scripts executed after login • Interactively by user • Also known as Environment / System variables • .bash_profile initialization file contains definitions and assignments of parameter variables.
Shell: Variables • Each shell variable is used for a specific purpose • A shell variable is typically entered in uppercase • To get its value, you precede the shell variable name with a $, as in $PWD • The set command shows the complete list
Learning about shell variables Examples of shell variables: • PWD – the most recent working directory set with the cd command • OLDPWD – the previous working directory set with the cd command • BASH – the full path of the bash shell • HOME – each user’s home directory, typically /home/username, where username is a user’s login name • HOSTNAME – the current hostname of a Linux system
Expansion • Expansion is the process of using meta characters and special symbols to change the given text • Simple examples: • Variable Expansion • $HOME expands into current user’s home directory, • $BASH expands to give the full path of the bash shell • The types of expansion discussed: • Parameter and variable • Command substitution
Parameter and Variable Expansion • Parameter expansion substitutes values for parameter or variable names • Parameters and variables are names that contain data values • Example: • echo $x will display the contents of a variable named x • Notice=“Meeting will be held tomorrow” • Echo $Notice Use of braces {…} allows one to mix variables and numbers. Example: echo ${EmployeeName} will display an employee’s name on the screen
Expansion – Command Substitution Command substitution allows you to substitute the output of a command in place of the command itself Two forms: • Use $(command) Example: echo "Today is " $(date) • Surround the command with a single back quote as in `command` Example : Mycmd = `ls *.c` echo $Mycmd
Vi Editor • Early days we use Ed that was a line editor • Ed was not so user friendly • Improved version of Ed is Ex • Ex is user friendly • Ed is an ugly toad then ex is less ugly toad • Vi is screen editor • Vi shows you as much of file as it can fit on the screen • Vi makes it easier to create and editing the file
Vi Editor- Mode • Command mode • In this mode the keys hit by the user are not displayed on the screen • Insert Mode • This mode permits insertion of the new text • This mode also known as the input-text mode • Ex-Command mode • This mode permits us to give commands at the command line
Vi Editor…. • To move from command mode to insert mode use i key • To move from insert mode to command mode use Esc key • To quit from vi after saving use ZZ • To create a file in vi vi file name • It shows you a full screen view of your file by using the insert mode you can insert text in your file • By default mode of vi is command mode
Shell Script • Normally shells are interactive i.e. shell accept command from you (via keyboard) and execute them. • But if required a set of related commands can be run by storing them to text file and telling the shell to execute this text file. • This is known as shell script. • Definition: • "Shell Script is series of command written in plain text file. Shell script is just like batch file is MS-DOS but have more power than the MS-DOS batch file."
Why to write shell script? • Shell script can take input from user, file and output them on screen. • Useful to create our own commands. • Multiple commands can be bound by means of control constructs to define a logical flow of control. • Shell scripts execute commands sequentially. • You can alter the sequential order with decisions, loops and functions • Shell scripts • combine programming logic with operating system commands • help in automating job duties
Creating shell scripts • Use any editor like vi or gedit to write shell script. • After writing shell script set execute permission for your script as follows • Syntax: • chmod permission script-name • Examples:$ chmod +x script-name$ chmod 755 script-name • Note:This will set read write execute(7) permission for owner, for group and other permission is read and execute only(5).
Executing shell scripts Syntax: $ shscript-name or$ ./script-name Examples: $ shscr or$ ./scr
User Define Variable Syntax:variable name=value • Variable name must begin with Alphanumeric character or underscore character (_) • Don't put spaces on either side of the equal sign when assigning value to variable • Variables are case-sensitive, just like filename in Linux • NULL variable can be defined as: $ varname=“ ” or varname= ‘ ‘ or varname= • $ a=20 $ echo $a will print the value of a on the screen
User Define Variable • All the shell variables are string variable a=20 is a string of characters 2 and 0 • We can not perform Arithmetic on variable • If a variable contain more then one word then assignment must be made using double quotes $c= “hello how” • We can carry out more then one assignment in a line $ name=ram age= 20 • We can echo more then one variable in one line $ echo $name $age • All variable define inside a shell script die as execution of script is over
Positional Parameters • To convey the information to a program through command line • $1 to $9 are the parameters known as positional parameter • $$ filename hello how are you file name $0 hello $1 how $2 are $3 • By using Echo we can print the value of these • We can use SET command old value will be discarded and we can assign new value $ set yes I can do Now the old value will be replaced by the new
Positional Parameters …. • A shell script using command line argument to copy the content of a file into another and display it on screen • $ vi copy cp $1 $2 cat $2 • Execute it by using the following command $ sh copy file1 file2 • During the execution content of file1 goes to $1 and file2 to $2 • Content of file2 will be displayed on the screen
Shell Arithmetic • To perform Arithmetic in shell script we use expr • exprdeal with integer arithmetic only • expr op1 math-operator op2Examples: $ expr 1 + 3$ expr 2 - 1$ expr 10 / 2$ expr 20 % 3$ expr 10 \* 3$ echo `expr 6 + 3`
Shell Arithmetic • Expr work with integer only so for float arithmetic we use bc • Use of bc a=10.5 b=3.7 c=`echo $a + $b | bc` echo $c • bc $a + $b is not a valid statement that’s why we piped the addition to bc that deal with the rest process
Exit Status In Linux when a particular command/shell script is executed, it returns two type of values, signifying success or failure This value, returned via return statement, is known as Exit Status. These values can be used to check whether command or shell script executed successfully or not. • If return value is zero (0), command is successful. • If return value is nonzero, command is not successful or some sort of error executing command/shell script. $? can be used to find the exit status of last executed command.
Exit status : example For e.g. (This example assumes that unknownfile does not exist ) $ rm unknownfile It will show error as followsrm: cannot remove `unkownfile': No such file or directoryand after that if you give command $ echo $? it will print nonzero value to indicate error The value of $? can be used in scripts for decision making
Shell Grammar - I A blank is a space or tab used to separate items A word (token) is a sequence of characters considered to be a single unit to the shell A name (identifier) is a word consisting of letters, numbers and underscore A meta character is a character that, when unquoted, separates words A Control Operator is a token that performs control function.
Shell Grammar - II Metacharacter: Examples • | - the pipe symbol allows you to pass output to another command • & - the ampersand allows you to run a process in the background • ; - the semicolon allows you to sequence commands • <- less than redirects input • > - greater than redirects output
Shell Grammar - III Control operators: • || - executes a command depending upon failure of another • && - executes a command depending upon success of another A reserved word has special meaning to the shell and cannot be used for another purpose. Example: if, then, else, fi
Command Separators The && Operator • Causes a command to execute only if the preceding command completes successfully (exit status of 0) • Example: rm file4.txt && ls • The ls command will only execute if rm file4.txt completes successfully The || Operator • Causes a command to execute only if the preceding command completes unsuccessfully (exit status of 1) • Example: rm file4.txt || pwd • The ls command will only execute if rm file4.txt completes unsuccessfully
Operators Logical • -a: and • -o: or • !: not Comparison • -eq, -ne, -lt, -gt, -le, -ge: Numerical Comparison • =, != : String comparison • -z: check string against null
If statement The shell requires you to follow strict syntax when implementing the if statement The syntax of the if statement follows: if [condition] then Statements else Statements fi if statements can be nested if required
Test command • Test command will help the shell to decide whether to execute the if block or the else block Echo enter the number Read num if test $num –lt 6 then echo hello else echo how fi
Test….. • Test command carry out three types of test • Numerical test • String test • File test • Numerical test
Test….. • File Test • Will deal with the file test with if statement
Test…. • String Test • Will deal with string test with if statement
String test into action str1= “good” str2=“bad” str3= [ $str1 = $str2 ] echo $? 1 // failure [$str1!= str2 ] echo $? 0 // success [-n str1 ] echo $? 0 // success [ -z “str3” ] echo $? 0 // success
String test in to action [ -z $str3 ] echo $? Error: test argument expected • A null string is ignore by the shell • If we place a string in “ “ then it is executed by the shell • Anytime a error is occurred in script the shell abandons the rest of the program str1=“ hello how” str2=“ are you” [ $str1= $str2] Echo $? Error : unknown operator how • Error is there because a two word string is assign to string so for testing such a string we must place double quotes with string [ “$str1” = “$str2” ] is a valid check
elif clause in an if statement The optional elif clause allows you to further test an if statement if [condition] then Statements elif [condition] then Statements else Statements fi fi
The case statement Another decision structure Use when a decision is based upon multiple inputs Syntax: case word in Pattern1) statements;; Pattern2) statements;; esac
Case….. • Shell Script for case statement Echo “ enter a number from 1 to 4” read n case $n in 1) echo enter1 ;; 2) echo enter 2 ;; 3) echo enter3 ;; *) echo this is default mode ;; esac
Case With Pattern matching echo enter any character read char case $char in [a-z]) echo you type a small case letter ;; [A-Z]) echo you enter a capital letter ;; [0-9]) echo you enter a number ;; *) echo you entered more then one character ;; esac
Case..be aware of… • Always use default choice as a last choice • Case is a better choice because it offer a better way of writing the program • Always use ;; to mark the end of choice, in final case ;; is not mandatory but it cause no harm if we use it in last case • The choice of case can have only a specific alternative or a group of alternatives • We can not have a choice like $num –lt 10 in case • Case dominate if because it lead to a more structured program and the level of indentation is more manageable
The while statement A set of statements is executed till a condition evaluates to true while [ condition ] do statements done