Scripting
Scripting
book comes with Free Access to Online Shell Scripting tutorial (worth of $49). Every concept has been
explained with lot of examples so you would know when to apply it and how to apply them in real time world. Also free
course includes downloadable ebook containing all concepts and related examples.
You will become a shell programming expert with complete knowledge of shell programming
You will learn with more than 60+ programming & real world examples
You will know How to make use of Mathematical, String and Logical operators in shell script to make decisions
How to Create functions in shell scripts and improve reusability
You will learn How to make use of Exit values to determine shell script output status
How to Accept input from a user and then make decisions on that input.
You will know How to make use of Expressions in shell scripts
Dealing with command line arguments and use of it with examples
You will learn How to make use of Pipe & Process concepts while creating shell scripts
Use of utilities like cut, paste, join, tr in shell scripts with examples
Practice exercises with solutions so you can start using what you learn right away.
Real-world examples of shell scripts, how it is used in corporate world.
Last but not least, you will get downloadable material containing the scripts and topics contents
PS: Free access to tutorial link is given at end of book, please check index for same.
Thank you!
Contents
Shell Introduction
Variables
Variables in Shell
Wild cards
Pipe Concept
Mathematical operators
Logical Operators
Conditional statements
What is Processes
What is function?
Need of function?
Function examples
Essential Utilities
Terminating Processes
Shell Introduction
The shell acts as an interface between the user and the kernel. When a user logs in, the
login program checks the username and password, and then starts another program called
the shell. The shell is a command line interpreter (CLI). It interprets the commands the
user types in and arranges for them to be carried out. The commands are themselves
programs: when they terminate, the shell gives the user another prompt (% on our
systems).
Important shells in market
Normally shells are interactive. It means shell accept command from you (via keyboard)
and execute them. But if you use command one by one (sequence of ‘n’ number of
commands) , the you can store this sequence of command to text file and tell the shell to
execute this text file instead of entering the commands. This is known as shell script.
Shell script defined as:”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.
● In this tutorial we are going to get started with shell programming, how to
write script, execute them etc. We will get started with writing small shell script,
that will print “Hello world” on screen.
● To write shell script you can use any editor supported like vi or mcedit.
● I will use vi editor: To open a new file in vi edit you can use the command vi
followed by the script name that you would want to save your file as.
● Note that shell scripts have an extension of .sh
vi hello.sh
● Before you can set execute the shell script, you need to set execute permission
for your script as follows:
syntax:
chmod permission your-script-name
Examples:
$ chmod +x your-script-name
syntax:
bash your-script-name
sh your-script-name
./your-script-name
Examples:
$ bash hello.sh
$ sh hello.sh
$ ./hello.sh
NOTE In the last syntax ./ means current directory, But only . (dot) means execute given
command file in current shell without starting the new copy of shell, The syntax for . (dot)
command is as follows
Syntax:
. command-name
Example:
$ . num_var
● Let us analyses the script we wrote. You can re-open the script vi hello.sh (Start
vi editor)
● In the script,
# My first shell script
# comment-text
● Next,
syntax:
echo “Message”
Variables
Variables in Shell
● RAM memory is divided into small locations, and each location had unique
number called memory location/address, which is used to hold our data.
How to define User defined variables (UDV)
variable_name=value
● a=10
● b=‘Hello’
System Variable example
● You can see system variables by giving command like $ set, some of the
important System variables are: Modify this table accordingly.
Rules for Naming variable name
Here are 4 rules you need to consider for naming variable name (Both UDV and System
Variable) .
2. Don’t put spaces on either side of the equal sign when assigning value to
variable.
In following variable declaration there will be no error
$ num_var=10
But there will be problem for any of the following variable declaration:
$ num_var =10
$ num_var= 10
$ num_var = 10
4. You can define NULL variable as follows (NULL variable is variable which has
no value at the time of definition) For e.g.
$ vech=
$ vech=””
Try to print it’s value by issuing following command
$ echo $vech
Nothing will be shown because variable has no value i.e. NULL variable.
How to print or access value of User defined variables
$variablename
or
echo $variablename
● Define variable vehicle and num as follows:
$ vehicle=Bus
$ num=10
$ echo $vehicle
● It will print ‘Bus’,To print contains of variable ‘num’ type command as follows
$ echo $num
Note: Do not try $ echo vehicle, as it will print vech instead its value ‘Bus’ and $ echo
num, as it will print n instead its value ‘10’, You must use $ followed by variable name.
Usage of Quotes - Concept & Examples
Example:
● It will print time as, 17:01:35.99 Can you see that the `date` statement uses
back quote?
Exit status value
● Simple, to determine this exit Status you can use $? special variable of shell.
Exit Status Demo
For e.g. (This example assumes that helloWorld.sh doest not exist on your hard drive)
$ rm helloWorld.sh
$ ls
$ echo $?
$ date
$ echo $?
$ echo hello
$ echo $?
How to Get Input from user
● If we would like to ask the user for input then we use a command called read.
This command takes the input and will save it into a variable.
Syntax:
read variable1, variable2,…variableN
#!/bin/bash
read varname
● This script would ask the user for his name and greet him.
● Run it as follows:
./hi.sh
Wild card
Meaning Examples
/Shorthand
$ ls /bin/[^a-o]
Redirection of Standard Input/Output
Redirection concept with >,>>,<
Most Unix system commands take input from your terminal and send the resulting
output back to your terminal. A command normally reads its input from a place
called standard input, which happens to be your terminal by default. Similarly, a
command normally writes its output to standard output, which is also your terminal
by default.
For e.g. $ ls command gives output to screen; to send output to file of ls command
give command.
Syntax:
Syntax:
Linux-command >> filename
$ ls > myfiles
Orange
mango
peas
Press CTRL + D to save.
Pipe Concept
● You can connect two commands together so that the output from one program
becomes the input of the next program. Two or more commands connected in this
way form a pipe.
● To make a pipe, put a vertical bar (|) on the command line between two
commands.
Syntax:
command1 | command2
5 Pipe examples used in real time world
$ who | sort
● Output of who command is given as input to sort command So that it will print
sorted list of users
print sorted list of users and output is sent to (redirected) list_of_user file
$ who | wc -l
Output of who command is given as input to wc command So that it will number of user
who logon to system
Output of who command is given as input to grep command So that it will print if
particular user name if he is logon or nothing is printed (To see particular user is
logon or not)
Executing multiple commands in single command line
● There are needs many a time to execute more than one commands on a line the
syntax to do this,
Syntax:
command1;command2
Examples:
$ time;whoami
$ time whoami
● for same purpose, you must put semicolon in between time and whoami
command.
Many times in our tutorial you will find following in if syntax
if <condition> ; then
commands
fi
since we are giving then on same line where is if condition we give ; before then otherwise same can be writtent without
; as below -
if <condition>
then
commands..
fi
Test or Expression command
Syntax:
● when you give expression without test command you just mention it in [
expression ]
● NOTE -Please make sure space after “[” and before “]”
Example 1 -
#
# Script to see whether argument is positive
#using mathematical operator gt, will see it in detail later
if test $1 -gt 0
then
echo “$1 number is positive”
fi
#NOTE -Please make sure space after “[” and before “]”
if [ $1 -lt 0 ]
then
● Run it as follows
$ ./check_postive.sh 7
● 7 number is positive
$ ./check_postive.sh -49
-49 number is Negative
$ check_postive
● If it is true(0) then test will return 0 and output will printed as 7 number is
positive but for -49 argument other echo statement printed.
● And for last statement we have not supplied any argument hence error
./check_postive: test: -gt: unary operator expected, is generated by shell , to avoid
such error we can test whether command line argument is supplied or not.
Expression list options & example
Here is a partial list of the conditions that test can evaluate.
Since test is a shell command, use “ help test ” to see a complete list.
you can either use it with expression within [ ] Or
with test command as shown in example 2
Expression Description
file1 -nt file2 True if file1 is newer than (according to modification time) file2
Example 2 -
if [ -f mytest.txt ]; then
echo “You have a mytest.txt. Things are fine.”
else
echo “Yikes! You have no mytest.txt!”
fi
echo “using test command”
if test -f mytest.txt
then
echo “Awesome! You have a mytest.txt. Things are fine.”
else
echo “O O! You have no mytest.txt!”
fi
fi
./ test_myfile.sh
rm mytest.txt
run again-
./ test_myfile.sh
similarly you may try all other options with test to verify various things. we will look that with our real time examples in
next chapters.
expr for expression evaluation
expr command is very commonly used to perform many arithmetic, logical or string operations in shell script.
You can do -
cnt =0
echo $cnt
echo $cnt
expr 1 + 2 + 3 + 4
10
expr 8 \* 9
72
Example 4 -
expr 8 % 5
3
expr - Comparison Operator concept & examples
You can use the following comparision operators with the expr command:
Value1 < Value2 : Returns 1 if Value1 is less than Value2. otherwise zero.
Value1 <= Value2 : Returns 1 if Value1 is less than or equal to Value2. otherwise zero.
Value1 > Value2 : Returns 1 if Value1 is greater than Value2. otherwise zero.
Value1 >= Value2 : Returns 1 if Value1 is greater than or equal to Value2. otherwise zero.
Value1 | Value2 : Returns Value1 if Value1 is neither null nor zero. Otherwise Value2.
Value1 & Value2 : Returns Value1 if both Value1 and Value2 is neither null nor zero. Otherwise 0.
expr 2 \< 3
1
expr 5 \<= 5
1
expr 3 \> 8
0
expr 3 \>= 8
0
expr 9 = 9
1
expr 9 != 81
1
expr 2 \| 6
2
expr 0 \| 7
7
expr 2 \& 7
2
expr 6 \& 4
6
expr 7 \& 0
0
expr 0 \& 4
0
expr - String Operator concept & examples
extract a portion of string. Here position is the character position in the string. length is the number of chracters to
server
If the chars string is found in the main string, then the index function returns the position of the chars. Otherwise it
returns 0.
If the chars string is found in the main string, then the index function returns the position of the chars. Otherwise it
returns 0.
Mathematical operators
● Depending on what type of work you want your scripts to do you may end up using arithmetic a lot or not
much at all. It’s a reasonable certainty however that you will need to use arithmetic at some point.
Normal Arithmetical/
Mathematical Operator
Meaning Mathematical But in Shell:
in Shell Script
Statements
Mathematical operators example
#!/bin/bash
# declare integers
NUM1=2
NUM2=2
NUM3=5
else
fi
else
fi
press ctrl+c
ls –l
./math_opr.sh
String Comparison operators
Operator Meaning
String Comparison operators example
Please explain code first in detail with concept then output with revisiting code why it showed that output.
#!/bin/bash
#declare strings
str1=“ABC”
str2=“XYZ”
str3=” “
else
fi;
else
fi;
if [ -n “$str2” ]; then
else
echo “str2 is NULL”
fi;
if [ -z “$str3” ]; then
else
fi;
ls –l
./ string_comparison.sh
Logical Operators
Operator Meaning
Not: This is logical negation. This inverts a true condition into false and vice versa.
AND – you can use –a or && (most common) both conditions need to be satisfied
if [ $condition1 ] || [ $condition2 ]
Logical Operators Example
str1=“ABC”
str2=“XYZ”
str3=“ABC”
else
fi;
else
fi;
else
fi;
ls –l
./ logic_opr.sh
Command Line Arguments
Why Command Line arguments required
$ rm {file-name}
● Here rm is command and file-name is file which you would like to remove. We
can now tell the rm command which file you would like to remove.
Command Line argument examples
Example 1
$ ls -a /*
● This command has 2 command line argument -a and /* is another. For shell
script,
$ any_script_name yoyo jar
Example 2
#!/bin/sh
#
(press ctrl+c to save and exit)
chmod777 demo_example.sh
We will be using command line arguments in many of our examples so please understand it properly.
You may not assign command line arguments in script so following is Invalid
$1 = ABC
$2 = “Name”
echo and read concept & example
In real time situations, shell script may need to interact with users. You can
accomplish this as follows:
Use command line arguments (args) to script when you want interaction i.e. pass
command line args to script as :
$ ./script_name.sh fo 4
where fo & 4 are command line args passed to shell script sutil.sh.
OR
Use statement like echo and read to read input into variable from the prompt. For e.g.
Write script as:
#
echo “Name please :”
read name
echo “Last Name please :”
read l_name
echo “Hello $name $l_name, How are you?”
Save it and run as
$ chmod 755 user_input
$ ./user_input
Conditional statements
if command concept & example
if condition or expression
then
fi
$ cat test.txt
$ echo $?
● The cat command return zero(0) i.e. exit status, on successful, this can be used,
in if condition as follows, Write shell script as
$ cat > showfile
#!/bin/sh
#
if cat $1
then
● if cat command finds test.txt file and if its successfully shown on screen, it
means our cat command is successful and its exist status is 0 (indicates success), So
our if condition is also true and hence statement echo -e “\n\nFile $1, found and
successfully echoed” is proceed by shell. Now if cat command is not successful
then it returns non-zero value (indicates some sort of failure) and this statement
echo -e “\n\nFile $1, found and successfully echoed” is skipped by our shell.
if…else…fi concept & example
if condition
then
else
fi
if…else…fi example
#!/bin/sh
#
if [ $# -eq 0 ]
then
echo “$0 : You must supply at least one integers”
exit 1
fi
if test $1 -gt 0
then
fi
Try it as follows:
$ chmod755 test_number.sh
$ test_number.sh 8
8 number is positive
$ test_number.sh -47
$ test_number.sh
$ test_number.sh 0
0 number is negative
● First script checks whether command line argument is given or not, if not given
then it print error message as “./ test_number.sh : You must give/supply one
integers“.
● The echo command i.e. echo “$0 : You must give/supply one integers”
● $0 will print Name of script
● And finally statement exit 1 causes normal program termination with exit
status 1 (nonzero means script is not successfully run).
Nested ifs concept & example
● You can write the entire if-else construct within either the body of the if
statement of the body of an else statement. This is called the nesting of ifs.
Nested ifs example
$ vi nestedif.sh
osch=0
read osch
if [ $osch -eq 2 ] ; then
fi
fi
$ chmod +x nestedif.sh
$ ./nestedif.sh
1. Mac
2. Linux
$ ./nestedif.sh
1. Mac
2. Linux
$ ./nestedif.sh
1. Mac
2. Linux
Select you os choice [1 or 2]? 3
● Note that Second if-else construct is nested in the first else statement. If the
condition in the first if statement is false the the condition in the second if
statement is checked. If it is false as well the final else statement is executed.
Multilevel if-then-else concept & example
if condition
then
elif condition1
then
elif condition2
then
else
#!/bin/sh
#
if [ $1 -gt 0 ]; then
elif [ $1 -lt 0 ]
then
echo “$1 is negative”
elif [ $1 -eq 0 ]
then
else
fi
$ ./Multi_if_elif 1
$ ./Multi_if_elif -5
$ ./Multi_if_elif 0
$ ./Multi_if_elif a
switch or case command concept
● we may wish to take different paths based upon a variable matching a series of
patterns. We could use a series of if and elif statements but that would soon grow to
be too long. Solution to this is case statement which can make things cleaner.
Syntax:
case $variable-name in
pattern1) command
..
command;;
pattern2) command
..
command;;
pattern2) command
..
command;;
patternN) command
…
..
command;;
*) command
…
..
command;;
esac
● The $variable-name is compared against the patterns until a match is found.
The shell then executes all the statements up to the two semicolons that are next to
each other. The default is *) and its executed if no match is found
switch or case command example
if [ -z $1 ]
then
elif [ -n $1 ]
then
# otherwise make first arg as rental
rental=$1
fi
case $rental in
“car”) echo “For $rental USD20 per mile”;;
“van”) echo “For $rental USD10 per mile”;;
$ chmod +x car_rental
$ car_rental van
$ car_rental car
$ car_rental Ford
$ car_rental cycle
● We will check first, that if $1(first command line argument) is given or not,
● if NOT given set value of rental variable to “*** Unknown vehicle ***”,
● For first test run its match with van and it will show output “For van USD10
per mile.”
● For second test run it print, “For car USD20 per mile”.
● And for last run, there is no match for Ford, hence default i.e. *) is executed
and it prints, “Sorry, I cannot get a Ford for you”.
● Please Note that: esac is always required to indicate end of case statement.
Loops Concept - for & while loop
Loops allow us to take a series of commands and keep re-running them until a
particular situation is reached. They are useful for automating repetitive tasks.
Loop defined as:
“Computer can repeat particular instruction again and again, until particular
condition satisfies. A group of instruction that is executed repeatedly is called a
loop.”
We will look at for loop and while loop.
Note that in each and every loop,
First, the variable used in loop condition must be initialized, then execution
of the loop begins.
A test (condition) is made at the beginning of each iteration.
The body of loop ends with a statement that modifies the value of the test
(condition) variable.
for loop concept
● for loops iterate through a set of values until the list is exhausted:
Syntax:
do
execute one for each item in the list until the list is
done
Syntax:
…..
…
repeat all statements between do and
for i in 1 2 3 4 5 6 7 8 9
do
$ chmod +x iterate.sh
$ ./iterate.sh
The for loop first creates i variable and assigned a number to i from the list of number
from 1 to 9, The shell execute echo statement for each assignment of i. (This is usually
know as iteration) This process will continue until all the items in the list were not
finished, because of this it will repeat 9 echo statements.
● To make you idea more clear let us consider one more example:
$ cat > multiply_table.sh
#!/bin/sh
#
#
if [ $# -eq 0 ]
then
echo “Error - Number missing form command line argument”
echo “Syntax : $0 number”
exit 1
fi
n=$1
for i in 1 2 3 4 5 6 7 8 9 10
do
$ ./multiply_table.sh 9
$ ./multiply_table
● For first run, above script print multiplication table of given number where i =
1,2 … 10 is multiply by given n (here command line argument 9) in order to
produce multiplication table as
9 * 1 = 9
9 * 2 = 18
…
..
9 * 10 = 90
● And for second test run, it will print message -
● This happened because we have not supplied given number for which we want
multiplication table,
● Hence script is showing Error message, Syntax and usage of our script. This is
good idea if our program takes some argument, let the user know what is use of the
script and how to used the script.
do
done
$ chmod +x for_example.sh
$ ./for_example.sh
Welcome 0 times
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times
● In above example, first expression (i = 0), is used to set the value variable i to
zero.
Nested for loop concept & example
● Loop statement can be nested. You can nest the for loop just like nested if.
Nested for loop example
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
$ vi nest_for.sh
do
do
echo -n “$i “
done
done
$ ./nest_for.sh
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
● Here, for each value of i the inner loop is cycled through 5 times, with the
variable j taking values from 1 to 5. The inner for loop terminates when the value
of j exceeds 5, and the outer loop terminals when the value of i exceeds 5.
while loop concept & example
● while loops can be much more fun! while an expression is true, keep executing
these lines of code.
Syntax:
while [ condition ]
do
command1
command2
command3
..
….
done
while loop example
#!/bin/sh
#
#Script to test while statement
if [ $# -eq 0 ]
then
fi
n=$1
i=1
while [ $i -le 10 ]
do
echo “$n * $i = `expr $i \* $n`”
i=`expr $i + 1`
done
$./While_loop 9
do Start loop
9 * 1 = 9
9 * 2 = 18
echo “$n * $i = `expr $i \* $n`”
….
Part I - Practical Shell Script Examples Explained
Please explain following examples as much details of programming knowledge for logic development of students, you
may do more echo or iteration charts to explain and develope programming skills of students.
Print incremental numbers
1 2 3 4 5 6 7
k=1
while test $k != 8
do
echo “$k “
k=`expr $k + 1`
done
n..8 7 6 5 4 3 2 1
Print Fibbonaci series
The next number is found by adding up the two numbers before it.
There should be some limit to find series so we will limit - how many numbers you want to see in series by var_num
variable in following example.
if [ $# -eq 1 ]
then
var_num=$1
else
echo -n “Enter a Number :”
read var_num
fi
f1=0
f2=1
echo “The Fibonacci sequence for the Number $var_num is : “
for (( k=0;k<=var_num;k++ ))
do
echo -n “$f1 “
fn=$((f1+f2))
f1=$f2
f2=$fn
done
Create repeating pattern using for loop
1
22
333
4444
55555
666666
Drawing Incremental Pattern
1
12
123
1234
12345
123456
For example if user enter 123 as input then 321 is printed as output.
example -
123
first iteration reminder = 3
sd = 3
first iteration digit = 12
second iteration reminder = 2
sd =2
second iteration digit = 1
sd =1
script -
echo “Enter number : “
read num
# store single digit
sd=0
# store number in reverse order
rev=””
# store original number
ori_num=$num
# while loop to calculate the sum of all digits
while [ $num -gt 0 ]
do
sd=$(( $num % 10 )) # to get Remainder
num=$(( $num / 10 )) # to get next digit
# store previous number and current digit in rev variable
rev=$( echo ${rev}${sd} )
done
echo “$ori_num in a reverse order is : $rev”
Process Concept & Commands
What is Processes
● When you execute a program on your UNIX system, the system creates a
special environment for that program. This environment contains everything
needed for the system to run the program as if no other program were running on
the system.
$ ls -lR
Why Process required
● As You know Linux is multi-user, multitasking Os. It means you can run more
than two process simultaneously if you wish. For e.g. To find how many files do
you have on your system you may give command like:
$ ls / -R | wc -l
● This command will take lot of time to search all files on your system. So you
can run such command in Background or simultaneously by giving command like
$ ls / -R | wc -l &
● The ampersand (&) at the end of command tells shells start process (ls / -R |
wc -l) and run it in background takes next command immediately.
● “An instance of running command is called process and the number printed by
shell is called process-id (PID), this PID can be use to refer specific running
process.”
Linux Command Related with Process
kill {PID} To stop any process by PID i.e. to kill $ kill 1012
process
process
ps ax | grep process- To see if a particular process is For e.g. you want to see whether
U-want-to see running or not. For this purpose you Apache web server process is
have to use ps command in running or not then give command
combination with the grep command
$ ps ax | grep httpd
Filter Concept & Example
● When a program takes its input from another program, performs some
operation on that input, and writes the result to the standard output, it is referred to
as a filter.
● For e.g.. Suppose you have file called ‘test.txt’ with 100 lines data, And from
‘test.txt’ you would like to print contents from line number 20 to line number 30
and store this result to file called ‘test_backup.txt’ then give command:
$ tail +20 < test.txt| head -n30 >test_backup.txt
● Here head command is filter which takes its input from tail command (tail
command start selecting from line number 20 of given file i.e. test.txt) and passes
this lines as input to head, whose output is redirected to ‘hlist’ file.
● Here uniq is filter which takes its input from sort command and passes this
lines as input to uniq; Then uniqs output is redirected to “u_sname” file.
User Defined Functions
What is function?
● It’s a small chunk of code which you may call multiple times within your
script.
● They are particularly useful if you have certain tasks which need to be
performed several times. Instead of writing out the same code over and over you
may write it once in a function then call that function every time.
Syntax:
function-name ( )
{
command1
command2
…..
…
command n
return
}
Need of function?
Function examples
Example 1
#!/bin/bash
# Basic function
print_something () {
}
print_something
Function example 2
Passing Arguments
It is often the case that we would like the function to process some data for us. We may
send data to the function in a similar way to passing command line arguments to a script.
We supply the arguments directly after the function name. Within the function they are
accessible as $1, $2, etc.
arguments_example.sh
#!/bin/bash
print_something () {
echo Hello $1
return
print_something Tim
print_something Kush
Sending unwanted output of program
● This is a special Linux file which is used to send any unwanted output from
program/command. It discards all data written to it without displaying it on screen.
Syntax:
Example:
● Output of above command is not shown on screen it will send to this special
file instead.
When you can use /dev/null-
2. When you write cron jobs (shell scripts executed by Unix/Linux scheduler automatically )
Usually cron sends an email for every output from the process started with a cronjob.
So by writing the output to /dev/null you prevent being spammed if you have specified your adress in cron.
Conditional command execution with && || operators
7. Logical AND operator can be used with more than 1 conditions. Also known as
&&
Syntax:
command2 is executed if, and only if, command1 runs successfully which means returns
an exit status of zero.
Example 1: Create folder, if the folder creation is successful, then only change the directory.
Like this, you can use it at various places effectively to save your valuable time.
Conditional commands execution using || operator
Syntax:
command1 || command2
command2 is executed if and only if command1 fails which means if command1 returns a
non-zero exit status.
Example 1 –
Example 2 –
Essential Utilities
● Cut command in unix (or linux) is used to select sections of text from each line
of files.
Usage: cut OPTION… [FILE]…
Mandatory arguments to long options are mandatory for short options too.
cut—help
3. Let us now create a file.txt with some random data. Say we want to get the 4th
column, or from column 4 to 6.
cat > myfile.txt
unix or linux os
is unix good os
is linux good os
xo
ui
ln
● Say we want to separate the text by a delimiter.
● Write lines consisting of the sequentially corresponding lines from each FILE,
separated by TABs, to standard output.
Usage: paste [OPTION]… [FILE]…
vi hello.txt
hello friend,
vi bye.txt
For each pair of input lines with identical join fields, write a line to standard
output. The default join field is the first, delimited by whitespace.
Usage: join [OPTION]… FILE1 FILE2
● Let us create 2 random file and we will index each line. The idea is to get a
common pointer in both files to join them.
vi hello.txt
1 hello
1 Hello bye
tr utility concept & example
tr utility concept
-s, —squeeze-repeats replace each input sequence of a repeated character that is listed
in SET1 with a single occurrence of that character
● A quick simple look at an example. Say we want to convert letter from lower
case to upper case.
tr a-z A-Z
hello
HELLO
^C
uniq utility concept & example
● Filter adjacent matching lines from INPUT (or standard input), writing to
OUTPUT (or standard output).
Mandatory arguments to long options are mandatory for short options too.
delimit-method={none(default),prepend,separate}
● uniq command removes duplicate adjacent lines from sorted file while sending
one copy of each second file.
Examples
unix
linux
linux
mac
windows
will show which lines appear more than once in names file.
Part 3 - Practical Shell Script Examples Explained
shell or bash script to delete old files
This will delete all the files except the latest 5 files.
modification time. i.e., the most recently modified files are first,
sed -e ‘1,10d’ deletes the first 10 lines, ie, the 10 newest files.
shell or bash script to archive files
The shell script will move the old file to tar archive and place the new one in
#!/bin/bash
oldfilename=$1
newfilename=$2
month=`date +%B`
year=`date +%Y`
prefix=“example”
archivefile=$prefix.$month.$year.tar
if [ -e $archivefile.gz ]
then
# compressed archive
gunzip $archivefile.gz
gzip $archivefile
else
fi
mv $newfilename $oldfilename
shell or bash script to rename files
do
mv “$file” “${file/_t.png/_tuhina.png}”
done
shell or bash script to copy files
cd /home/kishs/practice/examples
for f in *.png
do
cp $f /home/kishs/practice/${f%.csv}$(date +%m%d%y).csv
done
shell or bash script to create directory
read dirname
if [ ! -d “$dirname” ]
then
mkdir ./$dirname
fi
shell or bash script to delete file
#!/bin/bash
read filename
if [ -f $filename ]
then
rm filename
fi
shell or bash script to read file line by line
#!/usr/bin/bash
filename=”$1”
do
name=$line
shell or bash script to list files in a directory
do
echo $entry
done
shell or bash script to move file to another location
This script will move the files with extension .png to the specified location.
cd /home/kishs/practice/examples
for f in *.png
do
mv $f /home/kishs/practice/examples/apple/
done
shell or bash script to get cpu usage of a user
Top Command - top provides an ongoing look at processor activity in real time. It displays a listing of the most CPU-
intensive tasks on the system, and can provide an interactive interface for manipulating processes.
When you tried out the ls command to list directory contents, you started
a process.
You need to use the ps command, pstree command, and pgrep command
ps aux | less
pgrep looks through the currently running processes and lists the process IDs
pgrep -u kish
Sending signal to Processes
important event that has occurred. The events can vary from user requests to
illegal memory access errors. Some signals, such as the interrupt signal,
indicate that a user has asked the program to do something that is not in the
You can send various signals to commands / process and shell scripts using
Terminating Processes
fg jobid
kill –l
kill command Examples
The kill command can send all of the above signals to commands and process.
process.
kill -9 123
killall sends a signal to all processes running any of the specified commands .
killall processName
Shell signal values
Signals force the script to exit. You must know signal and their values while
writing the shell scripts. You cannot use (trap) all available signals.
Some signals can never be caught. For example, the signals SIGKILL (9)
kill –l
kill -l SIGTSTP
more /usr/include/linux/signal.h
Below is the commonly used signal numbers, description and whether they
The trap statement
trap defines and activates handlers to be run when the shell receives signals
trap ‘action’ 15 2 8 20
Try the following example at a shell prompt (make sure abc.txt doesn’t exits).
file=abc.txt
rm $file
Sample output:
trap
How to clear trap
trap - signal
file=abc.txt
trap
trap - SIGINT
trap
trap - 1 2 3 15
trap
trap statements to catch signals and handle errors in a script
#!/bin/bash
a=1
while [ $a -eq 0 ]
do
clear
echo “––––––––––-”
case $choice in 1)
2) w
esac
done
Get here - Free Access to Online tutorial
Click on below link or copy paste in your browser -
https://www.udemy.com/unix-bash-shell-scripting-tutorial-shell-programming-examples-linux/?couponCode=k1
or
CLICK HERE