A shell is a program that interprets commands and acts as an interface between application layer and kernel of OS A Linux shell is command interpreter that interprets a user command which are directly entered by user or which can be read from a file called as shell programming or shell.
You can get the name of your shell prompt, with following command :
Shell Scripts
Syntax: #echo $SHELL Output: /bin/bash When a group of commands has to execute regularly, it isbetter to store in a file. All such files are called shell scripts, shell program, or shell The extension is .sh is used for shell program
scripting.
You can get the name of your shell prompt, with followingprocedures.
Steps to create shell scripts
1. Open the terminal. Go to the directory where you want tocreate your script.
2. Create a file using vi editor(or any other editor). Name thescript file with extension .sh
3. To run your script in a certain shell, start your script with #!followed by the shell name. The sign #! is called she-bangand is written at top of the script. E.g. #! /bin/bash
4. Write some code
5. Save the script file as filename.sh 6. Make the script executable with command #chmod +x <fileName>
6. 7. Run the script using ./<fileName>
7. followed by the shell name. The sign #! is called she-bang
#chmod +x first.sh
First Shell Script
Output: Hello World
#vi first.sh
#! /bin/bash
echo “Hello World”
echo “Writing Shell Script is very easy!!!”
#./first.sh
Writing Shell Script is very easy!!!
Shell Scripting Variables
Scripts can contain variables inside the script.
A variable is a character string to which we assign a value. The value assigned could be anumber, text, filename etc Variable Names:
The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or theunderscore character ( _). By convention, Unix shell variables will have their names in UPPERCASE.
The following examples are valid variable names −
Following are the examples of invalid variable names − 2_VAR, -VARIABLE, VAR1-VAR2, VAR_A!
Defining Variables
Variables are defined as variable_name=variable_value . For example NAME=“Nilesh "The above example defines the variable NAME and assigns the value“Nilesh" to it. Variables of this type are called scalar variables. A scalar variable can hold only one value ata time. Shell enables you to store any value you want in a variable. For example − VAR1=“Pune" VAR2=100
_ABC, TOKEN_A, VAR_1, VAR_2
_ABC, TOKEN_A, VAR_1, VAR_2
Accessing Values
To access the value stored in a variable, prefix its name with the dollar sign ($) −For example, the following script will access the value of defined variable NAMEand print it on STDOUT − echo $NAME
Read-only Variables
Shell provides a way to mark variables as read-only by using the read-onlycommand. After a variable is marked read-only, its value cannot be changed. For example, the following script generates an error while trying to change the valueof NAME − readonly NAME The above script will generate the following result − /bin/sh: NAME: This variable is read only.
#!/bin/sh
NAME=“Nilesh"
Shell provides a way to mark variables as read-only by using the read-only
#!/bin/sh
NAME=“Nilesh"
NAME=“Patil“
Unsetting Variables
Unsetting or deleting a variable directs the shell to remove the variable from the listof variables that it tracks. Once you unset a variable, you cannot access the stored value in the variable. Following is the syntax to unset a defined variable using the unset command −unset variable_name You cannot use the unset command to unset variables that are marked readonly. Linux - Special Variables: The following table shows a number of special variables that you canuseinyourshell scripts 1. $0-The filename of the current script.
2. $n -These variables correspond to the arguments with which a script was invoked.Here n is a positive decimal number corresponding to the position of an argument(the first argument is $1, the second argument is $2, and so on). 3. $#- The number of arguments supplied to a script.
4. $?- The exit status of the last command executed.
The following table shows a number of special variables that you can use in your
Command-Line Arguments:
The command-line arguments $1, $2, $3, ...$9 are positional parameters,with $0 pointing to the actual command, program, shell script, or functionand $1, $2, $3, ...$9 as the arguments to the command. Following script uses various special variables related to the command lineecho "File Name: $0"
echo "First Parameter : $1"
echo "Total Number of Parameters : $#“ Here is a sample run for the above script − #./cmd_arg.sh 10 20
File Name : ./cmd_arg
First Parameter : 10
Second Parameter : 20
Total Number of Parameters : 2
#!/bin/sh
echo "Second Parameter : $2“
echo "Second Parameter : $2“
Exit Status
The $? variable represents the exit status of the previous Exit status is a numerical value returned by everycommand upon its completion. As a rule, most commands return an exit status of 0if theywere successful, and 1 if they were unsuccessful. Eg. #ls
#echo $? Will print 0
#cd Yogsh (Worng Dir name)
#echo $? Will print 1
command.
As a rule, most commands return an exit status of 0if they
Following are various operators supported by each shell.
Arithmetic Operators
+ (Addition)- Adds values.
- (Subtraction)- Subtracts right hand operand from left hand.
* (Multiplication)- Multiplies values on either side of the operator.
/ (Division)- Divides left hand operand by right hand operand.
% (Modulus)- Divides left hand operand by right hand operand and returnsremainder
Shell didn't originally have any mechanism to performsimple arithmeticoperations but it uses external programs, either awk or expr.
The following example shows how to add two numbers −
Shell Operators
val=`expr 2 + 2`
echo "Total value : $val”
The following points need to be considered 1. There must be spaces between operators and expressions. For example, 2+2 isnot correct; it should be written as 2 + 2.
2. The complete expression should be enclosed between ` ` called the backtick. Shell didn't originally have any mechanism to performsimple arithmetic
Relational Operators
Shell supports the following relational operators that are specific to numeric values.These operators do not work for string values unless their value is numeric. For example, following operators will work to check a relation between 10 and 20 aswell as in between "10" and "20" but not in between "ten" and "twenty". 1. -eq: Checks if the value of two operands are equal or not; if yes, then the conditionbecomes true. 2. -ne: Checks if the value of two operands are equal or not; if values are not equal,then the condition becomes true.
-gt: Checks if the value of left operand is greater than the value of right operand; ifyes, then the condition becomes true. 4.
-lt: Checks if the value of left operand is less than the value of right operand; if yes,then the condition becomes true.
-ge: Checks if the value of left operand is greater than or equal to the value of rightoperand; if yes, then the condition becomes true. 6.
-le: Checks if the value of left operand is less than or equal to the value of rightoperand; if yes, then the condition becomes true. It is very important to understand that all the conditional expressions should beplaced inside square braces with spaces around them. For example, [ $a <= $b ] is correct whereas, [$a <= $b] is incorrect.
Boolean Operators
The following Boolean operators are supported by theBourne Shell. Assume variable a holds 10 and variable b holds 20 then1.
! :- This is logical negation. This inverts a true conditioninto false and vice versa.
e.g. [ ! false ] is true.
-o :- This is logical OR. If one of the operands is true, thenthe condition becomes true. e.g. [ $a -lt 20 -o $b -gt 100 ] is true.
-a :-This is logical AND. If both the operands are true, thenthe condition becomes true otherwise false. e.g. [ $a -lt 20 -a $b -gt 100 ] is false.
File Test Operators
We have a few operators that can be used to test various properties associated with aUnix file. Assume a variable file holds an existing file name "test" the size of which is 100bytes and has read, write and execute permission on
-b file :-Checks if file is a block special file; if yes, then the condition becomes true.E.g. [ -b $file ] is false.
-c file :-Checks if file is a character special file; if yes, then the condition becomestrue. E.g.[ -c $file ] is false.
-d file :-Checks if file is a directory; if yes, then the condition becomes true. E.g.[-d$file ] is not true.
-f file :-Checks if file is an ordinary file as opposed to a directory or special file; ifyes, then the condition becomes true. E.g. [ -f $file ] is true.
-r file :-Checks if file is readable; if yes, then the condition becomes true. E.g. [ -r$file ] is true.
-w file :-Checks if file is writable; if yes, then the condition becomes true. E.g. [ -w$file ] is true.
-x file :-Checks if file is executable; if yes, then the condition becomes true. E.g. [ -x$file ] is true.
-s file :-Checks if file has size greater than 0; if yes, then condition becomes true.E.g. [ -s $file ] is true.
-d file :-Checks if file is a directory; if yes, then the condition becomes true. E.g.[-d]
Unix Shell supports conditional statements which are usedto perform different actions based on different conditions. We will now understand two decision-making statements
The if...else statements
If else statements are useful decision-making statements whichcan be used to select an option from a given set of options.
Shell Scripting if then else Unix Shell supports following forms of if…else statement −
if...fi statement
if...else...fi statement
here
if...elif...else...fi statement
The if...else statement
The case...esac statement
case Statement Syntax
The Bash case statement takes the following form:case EXPRESSION in
The case statment
PATTERN_1)
STATEMENTS
;
PATTERN_2)
STATEMENTS
STATEMENTS ;
PATTERN_N) STATEMENTS ;
)
STATEMENTS ;
esac
The while loop enables you to execute a set of commandsrepeatedly until some condition occurs. It is usually used when you need to manipulate the value ofa variable repeatedly. The While loop
do Statement(s) to be executed if command is true
Syntax:
while command
while command
done
The while loop is perfect for a situation where you need toexecute a set of commands while some condition is true. Sometimes you need to execute a set of commands until acondition is true. The Untill Loop
doStatement(s) to be executed until command is true If the resulting value is false, given statement(s) are executed. If the command is true then no statement will be executed andthe program jumps to the next line after the done statement.
Syntax:
until [command]
until [command]
done
for (( Initialization; condition; updation ))
The for Loop
Syntax of for like C programming language:
do
Statements;
done
Example:
f0or (( i=0; i<=5; i++) do
echo $i
done
SORT command is used to sort a file, arranging the records in aparticular order. SORT command sorts the contents of a text file, line by line. sort is a standard command line program that prints the lines ofits input or concatenation of all files listed in its argument list insorted order.
The sort command is a command line utility for sortinglinesoftext files. It supports sorting alphabetically, in reverse order, bynumber, by month and can also remove duplicates.
SORT command in Linux The sort command can also sort by items not at the beginning ofthe line, ignore case sensitivity and return whether a file issorted or not. Sorting is done based on one or more sort keysextracted from each line of input.
By default, the entire input is taken as sort key. Blank space isthe default field separator. The sort command is a command line utility for sortinglinesof
# sort abc.txt
This command does not actually change the input file, i.e. stud.txt but displays thecontent of file in ascending order. 2. -o Option : Unix also provides us with special facilities like if you want to writethe output to a new file, output.txt, redirects the output like this or you can also usethe built-in sort option -o, which allows you to specify an output file.
syntax: #sort inputfile.txt > filename.txt
#sort -o filename.txt inputfile.txt
-r Option Sorting In Reverse Order
You can perform a reverse-order sort usingthe -r flag. the -r flag is an option of the sort command which sorts the input fileinExamples of sort commands
the -r flag. the -r flag is an option of the sort command which sorts the input fileinreverse order i.e. descending order by default. 4. -n Option: This option is used to sort the file with numeric data present inside. E.g.# sort -n filename.txt 5. -nr option : To sort a file with numeric data in reverse order we can use thecombination of two options as stated below. E.g. # sort -nr filename.txt
-k Option
Unix provides the feature of sorting a table on the basis of any columnnumber by using -k option. Use the -k option to sort on a certain column. For example, use “-k 2” to sort on thesecond column. #sort –k colum number filename.txt
The cut command in UNIX is a command for cutting out the sections fromeach line of files and writing the result to standard output. It can be used to cut parts of a line by byte position, character and field. Basically the cut command slices a line and extracts the text. It is necessary to specify option with command otherwise it gives error. Letus consider a file having name state.txt which contains 5 names of theIndian states. $ cat state.txt
Arunachal Pradesh
cut command in Linux Examples of cut commands:
# cut –b 1,2,3 state.txt
# cut -b 1-3,5-7 state.txt (Range of bytes can also be specified using thehyphen(-) )
Andhra Pradesh
Andhra Pradesh
Assam
Bihar
Chhattisgarh
It uses a special form for selecting bytes from beginning uptothe end of the line: 3. $ cut -b 1- state.txt In this, 1- indicate from 1st byte to end byte of a line4. $ cut -b -3 state.txt
$ cut -c 1-7 state.txt
Above cut command prints second, fifth and seventhcharacter from each line of the file. cut -c 1-7 state.txt
Above cut command prints first seven characters of eachline from the file.
In this, -3 indicate from 1st byte to 3rd byte of a line In this, -3 indicate from 1st byte to 3rd byte of a line
It is used to join files horizontally (parallel merging) by outputting linesconsisting of lines from each file specified, separated by tab as delimiter, to thestandard output. Let us consider three files having name state, capital and number. state and capital file contains 5 names of the Indian states and capitalsrespectively. number file contains 5 numbers.
Paste command in Linux
Filters are programs that take plain as standard input, transformsit into a meaningful format, and then returns it as standard Linux has a number of filters.
Some of the most commonly used filters are explained below
head : Displays the first n lines of the specified text files. If thenumber of lines is not specified then by default prints first 10
Filters in Linux
tail : It works the same way as head, just in reverse order. Theonly difference in tail is, it returns the lines from bottom to up.
output.
sort : Sorts the lines alphabetically by default but there aremany options available to modify the sorting mechanism.
cat : Displays the text of the file line by line.
uniq : Removes duplicate lines. uniq has a limitation that it canonly remove continuous duplicate lines(although this can befixed by the use of piping) Syntax: # uniq [file path] #uniq /root/abc.txt When applying uniq to sorted data, it removes the duplicatelines because, after sorting data, duplicate lines come together.
wc: wc command gives the number of lines, wordsandcharacters in the data.
grep : grep is used to search a particular information from a text8. tac : tac is just the reverse of cat and it works the same way, i.e.,instead of printing from lines 1 through n, it prints lines nthrough 1. It is just reverse of cat command. 9. nl : nl is used to number the lines of our text data Syntax: #nl [File Path]
#nl /root/abc.txt
wc: wc command gives the number of lines, words and file.
Menu card just for you !
Select Your favourite topic to learn.
Comments
Post a Comment
Please give us feedback through comments