1 / 91

Unit -3 Shell Programming

Unit -3 Shell Programming. What is the Shell. Shell is a user level program. It is an command language interpreter that executes commands read from the standard input device (keyboard) or from a file.

ogden
Download Presentation

Unit -3 Shell Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Unit -3Shell Programming

  2. What is the Shell • Shell is a user level program. • It is an command language interpreter that executes commands read from the standard input device (keyboard) or from a file. • It is not part of system kernel, but uses the system kernel to execute programs, create files etc. • In MS-DOS, Shell name is COMMAND.COM which is also used for same purpose, but it's not as powerful as Linux Shells are!

  3. 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 (also called ksh) - Includes features from other shells - Includes advanced features from Ruby and Python languages like floating point arithmetic and arrays - File name completion - History feature

  4. 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.

  5. /etc/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.

  6. 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

  7. Shell: Responsibilities • Command Interpretation • Providing a scripting language • A process that provides runtime environment

  8. Simple architecture of a Shell User Lexical Analysis Expansion Execution Kernel

  9. 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

  10. 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.

  11. 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

  12. 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

  13. 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

  14. 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

  15. 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

  16. 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."

  17. 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

  18. 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).

  19. Executing shell scripts syntax: $ shscript-name or$ ./script-name Examples: $ shscr or$ ./scr

  20. User defined variables Syntax: variable name=value Rules for naming variables: • 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 (variable which has no value at the time of definition) can be defined as: • $ vech= • Do not use ?,* etc, to name your variable names Variable value can be accessed using $vname

  21. Shell Arithmetic Syntax: • expr op1 math-operator op2Examples: $ expr 1 + 3$ expr 2 - 1$ expr 10 / 2$ expr 20 % 3$ expr 10 \* 3$ echo `expr 6 + 3`

  22. 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.

  23. 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

  24. 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.

  25. 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

  26. 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

  27. 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

  28. Operators Logical • -a: and • -o: or • !: not Comparison • -eq, -ne, -lt, -gt, -le, -ge: Numerical Comparison • =, != : String comparison • -z: check string against null

  29. Decision Structures

  30. 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

  31. 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

  32. The case statement Another decision structure Use when a decision is based upon multiple inputs Syntax: case word in Pattern1) statements;; Pattern2) statements;; esac Can use * to match all patterns, ? to match a single character or […] for a range.

  33. Looping Structures

  34. The while statement A set of statements is executed till a condition evaluates to true while [ condition ] do statements done

  35. The while statement Use the break command to end a loop prematurely. Example: count=1 while [condition] do statements if [ $count –gt 3 ] then break fi statements done

  36. The until statement A set of statements is executed till a condition does not evaluate to true until [ condition ] do statements done

  37. The for statement The for statement syntax in the shell takes two forms: • Word list form: for variable in list do statements done • Arithmetic expression form: for ((var=init; test; incr)) do Statements done

  38. Understanding functions • Functions are self-contained blocks of code • Functions can accept values and return a result • Function code can be reused • Functions reduce redundancy • Functions provide for modular code

  39. Components of a function • General format of a function in the shell: function function-name () { list } • Function name is required • Either the keyword “function” or the parentheses are required but can use both • The left and right braces are required • The commands in list are any valid shell commands

  40. Function call Calling a function: • Done by using its name Example: function DisplayHello () { echo "hello" } DisplayHello

  41. Function basics • Functions are usually placed at the beginning of the script or prior to the function call • A function called prior to its definition will generate a “command not found” error • Functions are executed in context of the current shell (unlike shell scripts) • Functions can be exported to subshells using export -f

  42. Function parameters • On execution the parameters become the positional parameters • $0 remains unchanged • Variables are shared between function and its caller • return returns control back to the caller & the positional parameters are restored to their original value • Variables local to the function can be declared using local keyword

  43. Function : Example function testFunc () { for i in $* do echo $i done } for i in $* do echo $i done testFunc 1 2 3

  44. The return statement • Use the return command to cause a function return an exit status • General format: • returnn • Where n is the return status you specify • This value can be checked using $? • Typically 0 for success and non-zero for indicating cause of failure

  45. Arrays • Array is a variable containing a series of elements • Refer to elements using an integer called a subscript • Subscripts begin with 0 • Use an array when you have values that are similar in nature • All the data in the array can be accessed by referencing the whole array variable • A single element can be accesses by using its subscript value

  46. Declaring an array • Use the declare -a command to declare an array • Can use typeset -a command too • Example to declare an array named courses: • declare -a courses • declare -ia codes

  47. Assigning values to array elements • After declaring an array, you need to assign values to it • Example to set the first to elements of the courses array: • courses[0]="MCA" • courses[1]="B Tech." • Another method is to assign multiple elements as in: • courses=("MCA" "B Tech. ") • codes=(10 20 30) • Space acts as the element separator

  48. Using array elements • Syntax to refer to a single element of an array: • ${array-name[subscript]} • Example to display the sixth element (subscript 5) in the courses array: • echo ${courses[5]} • Using array elements as rvalue: • course=${courses[5]} • The expression $courses[5] • is treated as $courses followed by[5]

  49. Operations on an array • Reference all of the array elements: • echo ${array-name[*]} or echo ${array-name[@]} • Example: echo ${courses[*]} or echo ${courses[@]} • Determine the number of array elements: • echo ${#array-name[*]} or echo ${#array-name[@]} • Example: echo ${#food[*]} or echo ${#food[@]} • Determine an element’s length: • echo ${#array-name[subscript]} • Example: echo ${#food[2]} will give the length of 3rd element in the array. • Similarly echo ${#array} will give the length of the first lement in the array i.e. ${#array[0]}

  50. Getting values from the user • It is possible to use arithmetic operations and variable name substitution to determine a subscript number • Reading i-th element from user: • read -p "Enter $i the element" arr[$i] • Displaying i-th element to user: • echo ${arr[$i]} " "

More Related