Understanding Linux Shell Shell: A Command-Line Interpretor that connects a user to Operating System and allows to execute the commands or by creating text script. Process: Any task that a user run in the system is called a process. A process is little more complex than just a task. File: It resides on hard disk (hdd) and contains data owned by a user. X-windows aka windows: A mode of Linux where screen (monitor) can be split in small “parts” called windows , that allow a user to do several things at the same time and/or switch from one task to another easily and view graphics in a nice way. Text terminal: A monitor that has only the capability of displaying text stuff, no graphics or a very basic graphics display. Session: Time between logging on and logging out of the system. Types of Shell Bourne shell (sh) Korn shell (ksh) Bourne Again shell (bash) POSIX shell (sh) Bourne shell : The Bourne shell was one of the major shells used in early versions and became a de facto standard. It was written by Stephen Bourne at Bell Labs. Every Unix-like system has at least one shell compatible with the Bourne shell. The Bourne shell program name is “sh” and it is typically located in the file system hierarchy at /bin/sh. C shell : The C shell was developed by Bill Joy for the Berkeley Software Distribution. Its syntax is modelled after the C programming language. It is used primarily for interactive terminal use, but less frequently for scripting and operating system control. C shell has many interactive commands. Shell scripting advantages and disadvantages Advantages: To automate the frequently performed operations To run sequence of commands as a single command Easy to use Portable (It can be executed in any Unix-like operating systems without any modifications) Disadvantages: Slow execution speed compared to any programming languages A new process launched for almost every shell command executed -->-- FAQ | Extension of your Shell Script | We are using Bourne Shell | So .sh is the extension of the Script To get a Linux shell, you need to start a terminal. To see what shell you have, run: echo $SHELL. In Linux, the dollar sign ($) stands for a shell variable. The ‘echo‘ command just returns whatever you type in. The pipeline instruction (|) comes to rescue, when chaining several commands. Linux commands have their own syntax, Linux won’t forgive you whatsoever is the mistakes. If you get a command wrong, you won’t flunk or damage anything, but it won’t work. #!/bin/sh – It is called shebang. It is written at the top of a shell script and it passes the instruction to the program /bin/sh. #!/bin/sh -->-- First Line of your Script Process of writing and executing a script Open terminal. Navigate to the place where you want to create script using ‘cd‘ command. Cd (enter) [This will bring the prompt at Your home Directory]. touch hello.sh (Here we named the script as hello, remember the ‘.sh‘ extension is compulsory). vi hello.sh (nano hello.sh) [You can use your favourite editor, to edit the script]. chmod 744 hello.sh (making the script executable). sh hello.sh or ./hello.sh (running the script) Writing your First Script ========================== #!/bin/bash # My first script echo "Welcome to Unix World!" Sample Output ------------- Hello World! #!/bin/bash (is the shebang.) # My first script (is comment, anything following '#' is a comment) echo “Hello World!” (is the main part of this script) Writing your Second Script ========================== #! /bin/bash echo "Hello $USER" echo "Hey i am" $USER " and will be telling you about the current processes" echo "Running processes List" ps Create a file with above codes, save it to anything you want, but with extension “.sh“, make it executable and run it, from you terminal. Sample Output ------------- Hello tecmint Hey i am tecmint and will be telling you about the current processes Running processes List PID TTY TIME CMD 1111 pts/0 00:00:00 bash 1287 pts/0 00:00:00 sh 1288 pts/0 00:00:00 ps Writing your Third Script ========================== Moving to, write our third and last script for this article. This script acts as an interactive script. Why don’t you, yourself execute this simple yet interactive script and tell us how you felt. #! /bin/bash echo "Hey what's Your First Name?"; read a; echo "welcome Mr./Mrs. $a, would you like to tell us, Your Last Name"; read b; echo "Thanks Mr./Mrs. $a $b for telling us your name"; echo "*******************" echo "Mr./Mrs. $b, it's time to say you good bye" Sample Output ------------- Hey what's Your First Name? Avishek welcome Mr./Mrs. Avishek, would you like to tell us, Your Last Name Kumar Thanks Mr./Mrs. Avishek Kumar for telling us your name ****************************************************** Mr./Mrs. Kumar, it's time to say you good bye There are three types of shell variables available. They are, a)Local variables b)Environment variables c)Shell variables or Special variables Local variables: A local variable is a variable, its value will be visible to the current shell. Environment variables: An environment variable is a variable, its value will be visible to all the child shell's or child processes started from the shell. Shell variables or Special variables: A shell variable or special variable is a variable set by shell for its necessity. Some of these variables are environment variables whereas others are local variables Command Line Arguments Command line arguments are important part of writing scripts. Command line arguments define the expected input into a shell script. For example, we may want to pass a file name or folder name or some other type of argument to a shell script. Several special variables exist to help manage command-line arguments to a script: $# - represents the total number of arguments (much like argv) – except command • $0 - represents the name of the script, as invoked • $1, $2, $3, .., $8, $9 - The first 9 command line arguments • $* - all command line arguments OR • $@ - all command line arguments Evaluating Expr Shell scripts are not intended to do complex mathematical expressions. But expr program can be used to manipulate variables, normally interpreted as strings, asintegers. Consider the following "adder" script: sum=`expr $1 + $2` printf "%s + %s = %s\n" $1 $2 $sum Arithmetic Operators + (Addition) Adds values on either side of the operator `expr $a + $b` will give 30 - (Subtraction) Subtracts right hand operand from left hand operand `expr $a - $b` will give -10 * (Multiplication) Multiplies values on either side of the operator `expr $a \* $b` will give 200 / (Division) Divides left hand operand by right hand operand `expr $b / $a` will give 2 % (Modulus) Divides left hand operand by right hand operand and returns remainder `expr $b % $a` will give 0 = (Assignment) Assigns right operand in left operand a = $b would assign value of b into a == (Equality) Compares two numbers, if both are same then returns true. [ $a == $b ] would return false. != (Not Equality) Compares two numbers, if both are different then returns true. [ $a != $b ] would return true. Relational Operators -eq Checks if the value of two operands are equal or not; if yes, then the condition becomes true. [ $a -eq $b ] is not true. -ne Checks if the value of two operands are equal or not; if values are not equal, then the condition becomes true. [ $a -ne $b ] is true. -gt Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true. [ $a -gt $b ] is not true. -lt Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true. [ $a -lt $b ] is true. -ge Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true. [ $a -ge $b ] is not true. -le Checks if the value of left operand is less than or equal to the value of right operand; if yes, then the condition becomes true. [ $a -le $b ] is true. Boolean Operators ! This is logical negation. This inverts a true condition into false and vice versa. [ ! false ] is true. -o This is logical OR. If one of the operands is true, then the condition becomes true. [ $a -lt 20 -o $b -gt 100 ] is true. -a This is logical AND. If both the operands are true, then the condition becomes true otherwise false. [ $a -lt 20 -a $b -gt 100 ] is false. String Operators = Checks if the value of two operands are equal or not; if yes, then the condition becomes true. [ $a = $b ] is not true. != Checks if the value of two operands are equal or not; if values are not equal then the condition becomes true. [ $a != $b ] is true. -z Checks if the given string operand size is zero; if it is zero length, then it returns true. [ -z $a ] is not true. -n Checks if the given string operand size is non-zero; if it is nonzero length, then it returns true. [ -n $a ] is not false. str Checks if str is not the empty string; if it is empty, then it returns false. Condition and Looping IF THEN if command then command command ... command fi IF THEN ELSE if command then command command ... command else command command ... command fi Example if [ "$LOGNAME"="guna" ] then printf "%s is logged in" $LOGNAME else printf "Intruder! Intruder!" fi ELSE IF if command command command ... command then command command ... command elif command then command command ... command elif command then command command ... command fi SWITCH CASE Statement case var in pat) command command ... command ;; # Two ;;'s serve as the break pat) command command ... command ;; # Two ;;'s serve as the break pat) command command ... command ;; # Two ;;'s serve as the break esac Example #!/bin/sh case "$2" in "+") ans=`expr $1 + $3` printf "%d %s %d = %d\n" $1 $2 $3 $ans ;; "-") ans=`expr $1 - $3` printf "%d %s %d = %d\n" $1 $2 $3 $ans ;; "\*") ans=`expr "$1 * $3"` printf "%d %s %d = %d\n" $1 $2 $3 $ans ;; "/") ans=`expr $1 / $3` printf "%d %s %d = %d\n" $1 $2 $3 $ans ;; Execution sh myscript.sh 2 + 3 | ./myscript.sh 2 + 3 The for Loop The for loop provides a tool for processing a list of input. The input to the for loop is a list of values. Each iteration through the loop it extracts one value into a variable and then enters the body of the loop. the loop stops when the extract fails because there are no more values in the list. for var in "$@" do printf "%s\n" $var done for var in "$@" do if [ "$var" = "quit" ] then break fi printf "%s\n" $var done for var in "$@" do if [ "$var" = "me" ] then continue elif [ "$var" = "mine" ] then continue elif [ "$var" = "myself" ] then continue fi if [ "$var" = "quit" ] then break fi printf "%s\n" $var done While and Until Loop ls | sort | while read file do echo $file done Write a shell script sum.sh that takes an unspecified number of command line arguments (up to 9) of ints and finds their sum. Modify the code to add a number to the sum only if the number is greater than 10 #! /bin/sh sum=0 for var in "$@" do if [ $var –gt 10 ] then sum=`expr $sum + $var` fi done printf "%s\n" $sum -- run the script as % sh 2.1.sh 2 4 5 (or) .\sh2.1.sh 2 4 5