Sei sulla pagina 1di 30

VIDYABHARTI TRUST COLLEGE OF BBA & BCA.

UMRAKH
SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
Q

Explain the Mode of vi editor.

The vi has following modes:


1. Command mode
2. Input mode (Insert mode) and
3. ex mode (Last Line Mode)
Command Mode :

This is the mode where you can pass command to act on text, using most of the keys of
the keyboard.

Commands used to move the cursor, to delete or change part of the test, etc.

As soon as the command is entered, it is executed the Return key is not required.

Commands are also known as hot key.

The command must be valid command otherwise give unpredictable result.

Text (Input) Mode :

To enter into this mode, first press I.

When the vi editor is in the text mode, any key that is pressed by a user is considered
text.

In this mode, the characters types by the user.

The characters are inserted into the text at the cursor.

To add the text in a document, we should place the cursor at the desired location.

To place the cursor we must be in command mode.

Then we switch to the text mode and edit the text.

Last line(ex) Mode :

This mode used to handle files like saving file and perform substitution.

Pressing a : in the command mode invokes this mode.

We can then enter an ex mode command followed by enter.

After running command, we are back to the default command mode.

Explain booting sequence with init process. [ Extract point as per mark ]

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 1

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
A

There are 6 high level stages of a typical Unix booting process.


1) System startup(Hardware )
2) Boot loader Stage 1 (MBR loading)
3) Boot loader Stage 2 (GRUB loader)
4) Kernel
5) INIT
System Startup :

This is the first stage of booting process.

After you power on/Restart your machine, The first instruction it will run is to pass control
to BIOS (Basic Input/output System) to do POST(Power On Self-Test). Once the control goes
to BIOS it will take care of two things
1)

Run POST operation.

2) Selecting first Boot device.


Run POST Operation : POST is a processes of checking hardware availability. BIOS will have a
list of all devices which are present in previous system boot.
Selecting First Boot Device : Once the POST is completed BIOS will select the first boot
device and gives back the control to Processor(CPU).
Stage 2: MBR Loading
Once the BIOS gives control back to CPU, it will try to load MBR of the first boot device MBR.
MBR starting at the first sector on the first hard drive, loads its contents into memory, then
passes control to it.
Stage 3: GRUB Loader

In this stage GRUB (Grand Unified Boot loader) which is located in the first 30 kilobytes of
hard disk immediately following the MBR is loaded into RAM for reading its configuration
and displays the GRUB boot menu (where the user can manually specify the boot

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 2

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS

parameters) to the user.


GRUB loads the user-selected (or default) kernel into memory and passes control on to the
kernel. If user do not select the OS, after a defined timeout GRUB will load the default
kernel in the memory for starting it.

Stage 4: Kernel

Once the control is given to kernel, it act as a mediator of hardware and software

components.
Kernel once loaded into to RAM it always resides on RAM until the machine is shutdown.
Once the Kernel starts its operations the first thing it do is executing INIT process.

Stage 5: INIT

When init starts, it becomes the parent or grandparent of all of the processes that start up

automatically on your Unix system.


The first thing init does, is reading its initialization file, /etc/inittab.
This instructs init to read an initial configuration script for the environment, which sets the

path, checks the file systems, and so on.


Basically, this step takes care of everything that your system needs to have done at system

initialization: setting the clock, initializing serial ports and so forth.


Then init continues to read the /etc/inittab file, which describes how the system should be

set up in each run level and sets the default run level.
A run level is a configuration of processes.
Following are the available run levels
0 System shutdown
1 System administration mode.
2 Multiuser, without NFS
3 Full multiuser mode
4 unused
5 Graphical environment mode
6 reboot
All UNIX-like systems can be run in different process configurations, such as the single user
mode, which is referred to as run level 1 or run level S (or s). When system is booted , init

first enter into level 1 0r S.


In this mode, only the system administrator can connect to the system. It is used to perform

maintenance tasks without risks of damaging the system or user data.


Another run level is the reboot run level, or run level 6, which shuts down all running
services according to the appropriate procedures and then restarts the system.

Define process. Which command is used to know the status of process? Explain it

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 3

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
with giving example and its option. What are the 3 phases to create process?
A

Process is an instance of a running program.


It is said to be Born when the program starts execution and remains alive as long as the
program is active.
After execution is complete , the process is said to Die.
ps command is used to see the status of currently running process in system.
NOTE: ps command is explain above question please add it here.
Process Creation Phases

There are three distinct phases in the creation of process using three important system
calls:

fork( ) ,

exec( ) and

wait( )

Fork( )

A process in unix is created with the fork system call, Which creates a copy of
the process that invoke it.
The process that invokes the fork system call is parent process and the newly
created process is the child process.
fork() allocates entry in process table and assigns a unique PID to the child
process.
child gets a copy of process image of parent: both child and parent share the
same code following fork(), different data.
But fork() returns the PID of the child to the parent process and returns 0 to
the child process
For example, when you enter a command at the prompt, the shell first creates a
copy of itself. The image is practically identical to the calling process, except for

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 4

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
a few parameters like PID. The forking mechanism is responsible for the
multiplication of processes in the system.
Exec( )

The parent then overwrite the image that it has created with the copy of the
program that has to be executed.
This is done with the exec system call and the parent is said to exec the
process.
The parent then executes the wait system call to keep waiting for the child

Wait( )

process to complete.

When the child process has completed execution, it send a termination signal
to the parent.

The parent is then free to continue with other function.

Explain Special variable used in Shell programming

We can not use

certain non-alphanumeric characters in your variable names. This is

because those characters are used in the names of special Unix variables.

Special variables are reserved for specific functions.

For example: $ character represents the process ID number, or PID, of the current shell:
$echo $$

Above command would write PID of the current shell 29949

There are following types of special variable:


$0

The filename of the current script.

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


The number of arguments supplied to a script.

$*

All the arguments are double quoted. If a script receives two arguments, $* is

$@

equivalent to $1 $2.
All the arguments are individually double quoted. If a script receives two arguments,
$@ is equivalent to $1 $2.

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 5

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
$?

The exit status of the last command executed.

$$

The process number of the current shell. For shell scripts, this is the

process ID

under which they are executing.


$!

The process number of the last background command.

Following script uses various special variables related to command line


#!/bin/sh
echo "File Name: $0"
echo "First Parameter : $1"
echo "First Parameter : $2"
echo "Quoted Values: $@"
echo "Quoted Values: $*"
echo "Total Number of Parameters : $#"
Output: $./test.sh OM SAI
File Name : ./test.sh
First Parameter : OM
Second Parameter : SAI
Quoted Values: OM SAI
Quoted Values: OM SAI
Total Number of Parameters : 2
Q

Explain Associative Array With Example. (Mar/Apr-2015)

An associative array is an array which uses strings as indices instead of integers.


Syntax: array[string] = value
The subscript is often called the key and is associated with the value assigned to the
corresponding array element.

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 6

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
The key and values are stored internally in a table .
The array element are not stored in sequential order and when the content of the array are
displayed, they may not be in order we expect.

The first array associate name with age. In this array, the name identify each persons age.
The second array associates department number with the sales for that department. The
department number in this array are string.
The associate array structure has several design constraints that we must remember when
we use them
1. Index must be unique, means each index can be associated with an array value only
once.
2. The association of the index with its values is guaranteed.
3. There is no ordering imposed on the indexes. It means if we create an associate array
and print it, there is no guarantee that the element will be printed based on the order in
which the array was created.
4. An array index cannot be sorted. The data value can be sorted.
Creation of Associative Array
To gain insights about array let us create and access the elements of the array.
$ awk 'BEGIN { fruits["mango"]="yellow";
fruits["orange"]="orange"
print fruits["orange"] "\n" fruits["mango"]
}'
On executing the above code, you get the following result:

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 7

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
orange
yellow
In above example we have declared array namely fruits whose index is fruit name and value
is colour of the fruit. To access array element we have used array_name[index] format.
The special for loop is used to read through an associated array when string are used as
subscript or the subscript is not consecutive numbers.

Q
A

Explain string function of awk.


Name
tolower

Description
This function convert string into upper case to lower case.
Non alphabetic characters are left unchanged.

Syntax: tolower(string)

Toupper

For example:
tolower("MiXeD cAsE 123")
Output: mixed case 123
This function convert string into upper case to lower case.
Non alphabetic characters are left unchanged.

Syntax: toupper(string)

Length

For example:
tolower("MiXeD cAsE 123")
Output: MIXED CASE 123.
It determines the length of its argument.
Syntax: length(string)
If no argument is present, it assumes the entire line as argument.
Following statement is used to locate the records whose length exceeds 57
characters.
Awk F | length > 57 emp.txt
For example in emp.txt file 2nd field contain the name of employee. To list out
those employee whose name is less than 10 character.
Awk f | length($2) < 10 emp.txt
Locate line in file which contain line between 100 and 150 character

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 8

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
Awk f | length > 100 && length < 150 emp.txt

Substr

It extract a substring from a string. It has two format


Syntax:

substr(string, position)
substr(string, position, length)

If length is specified, it returns up to length character for position.


For example: we have a field which contain string abcde, we can use this
function to find out whether b is present or not
x = substr(abcde,2)
Output: bcde
x = substr(abcde,2,2)
Output: bc

Split

It Divide string into pieces separated by fieldsep and store the pieces in array
and the separator strings in the seps array
Syntax: split(string, array)
split(string, array, field seperator)
In first format, the field in a string are copied into an array. The first piece is
store in array[1], the second in array[2] and so on. The end of each field is
identified by a field separator character.
In second format, the field separator is specified as the parameter.
Before splitting the string, split() deletes any previously existing elements in
the arrays array.
For example: split("cul-de-sac", a, "-")
splits the string `cul-de-sac' into three fields using `-' as the separator. It sets
the contents of the array a as follows:

a[1] = "cul"
a[2] = "de"
a[3] = "sac"
Index

This searches the string in for the first occurrence of the string find, and
returns the position in characters where that occurrence begins in the string
in. Consider the following example:
Syntax: index(in, find)
For example:
$ awk 'BEGIN { print index("peanut", "an") }'
3
If find is not found, index returns zero.
Remember that string indices in awk start at one.

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 9

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
Q

Explain System Variable.(Oct/Nov-2014)

Without these built-in variables its very much difficult to write simple AWK code.
These variable are used to format output of an AWK command, as input field separator and
even we can store current input file name in them for using them with in the script.
AWK built-in variables are listed below in table
Variable

Description

NR

Current count of the number of input records.

NF

Keeps a count of the number of fields.

FILENAME

The name of the current input file.

FNR

No. of records in current filename.

FS

Contain the field separator character.

RS

Stores the current record separator or Row Separator.

OFS

Stores the output field separator.

ORS

Stores the output record separator or Output RS.

NR Variable

This variable keeps the value of present line number.

This will come handy when you want to print line numbers in a file.
$ cat emps
Tom Jones
Mary Adams

4424
5346

5/12/66 543354
11/4/63 28765

$ awk '{print NR, $0}' emps


1 Tom Jones
2 Mary Adams

4424
5346

// same line cat n emps.

5/12/66 543354
11/4/63 28765

NF Variable

NF gives you the total number of fields in a record.

Awk NF will be very useful for validating whether all the fields are exist in a record.

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 10

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS

The final value of a row can be represented with $NF.


$ awk '{print $2,$NF;}' employee.txt
Thomas $5,000
Jason $5,500
Sanjay $7,000

In the above example $2 and $5 represents Name and Salary respectively. We can get the
Salary using $NF also, where $NF represents last field. In the print statement , is a
concatenator.

How to print last field without knowing the number of field in file?
$ awk '{print $NF;}' employee.txt
$5,000
$5,500
$7,000
In the above example $NF represents last field.

FILENAME

This variable contain file awk command is processing.

Example: Print filename for each line in a given file.


awk {print FILENAME, NR, $0} abc.txt
abc.txt

Jones

2143
abc.txt

78
Gondrol

84
2321

77

56

58

FNR Variable

This variable keeps count of number of lines present in a given file/data.

This will come handy when you want to print no of line present in a given file.

This command is equivalent to wc -l command.

Example: Print total number of lines in a given file.

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 11

45

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
awk END{print FNR} db.txt
5
FS Variable

This variable is useful in storing the input field separator.


By default AWK can understand only spaces, tabs as input and output separators.
But if your file contains some other character as separator other than these mention

ones, AWK cannot understand them.


For example Unix password file which contain : as a separator. So in order to mention
the input filed separator we use this inbuilt variable.

Print first column data from db.txt file.:


awk {print $1} db.txt
John,29,MS,IBM,M,Married
Barbi,45,MD,JHH,F,Single
If you see entire file is displayed which indicates AWK do not understand db.txt file separator
,. We have to tell AWK what is the field separator.
$ awk BEGIN{FS=,}{print $1} db.txt

OFS Variable

This variable is useful for mentioning what is your output field separator which
separates output data.

Example: Display only 1st and 4th column and the separator between at output for
these columns should be $.
$ awk BEGIN{FS=,;OFS= $ }{print $1,$4} db.txt
Om $ IBM
Sai $ JHH
Ram $ BofA

RS Variable

Row Separator is helpful in defining separator between rows in a file. By default AWK

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 12

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS

takes row separator as new line. We can change this by using RS built-in variable.
Example: I want to convert a sentence to a word per line. We can use RS variable for
doing it.
$ echo Om Sai Ram | awk BEGIN{RS= }{print $0}
Om
Sai
Ram

ORS Variable

This variable is useful for defining the record separator for the AWK command output.
By default ORS is set to new line.

Example: Print all the company names in single line which are in 4th column.
$ awk -F, BEGIN{ORS= }{print $4} db.txt
IBM JHH BofA DELL SmartDrive

expr command .

expr is a command line Unix utility which evaluates an expression and outputs the
corresponding value.
The Bourne cell doesnt have any computing features. So it rely on external command expr
for that purpose.
Syntax: expr (expression)
expr evaluates integer or string expressions, including pattern matching regular expressions.
It is not working with floating point value.
The operators perform following function
Perform arithmetic operation on integers
Manipulating string.
Arithmetic Operator used with expr
Operator

Description

Addition - Adds values on either side of the operator

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 13

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS

Subtraction - Subtracts right hand operand from left hand operand

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 returns
remainder

Operand must be enclosed on either side by whitespace.


Observe that multiplication operator has to be escaped to prevent thte shell from interpreting
it as the filename metacharacter.
expr often used with command substitution to assign a variable. For example, we can set a
variable z to the sum of two number
$ x=6 y=2; z= `expr $x + $y`
$ echo $z
8
For example: $ expr 1 + 2
Output : 3
String Operation using expr
Expr can perform three important string functions.
Determine the length of the string.
Extract a substring.
Locate the position of a character in a string.
Length of the String
The regular expression .* signifies to expr that it has to print the number of

characters matching the pattern. Means give the length of the string.
$ expr omsairam : ,*
8

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 14

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
Here expr counted the number of occurances of any character (.*) .
Here space is require on either side of :.
Extracting the Substring
expr can extract a string enclosed by the escaped characters \( and \).
If we wish to extract 2 digit year from a 4 digit string, we must create a pattern group

and extract it this way


$ stg=2015
$ expr $stg : ` ..\(..\)`
Here ..\(..\) tells that first two character in the value of stg have to be ignored and two

characters have to be extracted from the third character position.


Locating Position Of Chracter
expr can also return the location of the first occurrence of a character in a string.
To locate the position of the character d in the string value of the stg, we have to
count the number of characters which are not d ( [^d]* ) followed by d.
$ stg = abcdefgh ; expr $stg : `[^d]*d`
4
Q

FOR LOOP with example.

The for loop operate on lists of items. It repeats a set of commands for every item in a list.
Syntax:
for var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
Done

In the above syntax:

for, in, do and done are keywords


Here var is the name of a variable.
word1 to wordN are sequences of characters separated by spaces (words). If it is missing
in the for statement, then it takes the positional parameter that were passed into the

shell.
Each time the for loop executes, the value of the variable var is set to the next word in the

list of words, word1 to wordN.


For example, if the list of values contains 5 items, the for loop will be executed a total of 5 times, once
for each item in the list. The current item from the list will be stored in a variable varname each time
through the loop. This varname can be processed in the body of the for loop.

#!/bin/sh
for var in 1 2 3 4 5
do
echo n $var

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 15

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
done
This will produce following result 1 2 3 4 5
There are two types of bash for loops available. One using the in keyword with list of
values, another using the C programming like syntax.
Bash For Loop using C like syntax

The second form of the for loop is similar to the for loop in C programming language,
which has three expressions (initialization, condition and updation).
Syntax
for (( expr1; expr2; expr3 ))
do
Body of the loop.
done

In the above bash for command syntax,

Before the first iteration, expr1 is evaluated. This is usually used to initialize variables for

the loop.
All the statements between do and done are executed repeatedly until the value of expr2 is

TRUE.
After each iteration of the loop, expr3 is evaluated. This is usually used to increment a loop
counter.

Explain Test Command

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 16

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
A

When we use if to evaluate expressions, we need the test statement because the true or false
values returned by expressions cant be directly handled by if.
test use certain operators to evaluate the condition on its right and returns either a true or
false exit status, which is then used by if for making decision.
In the if statement instead of explicitly mentioning the word test, we have placed the
condition within [ ] which is allowed.
Here we must provide space around the operators and operands.
test command can carry out following types of test

Numerical Test
String Test
File Test

Numerical Test : All relation operator is used as numeric comparison operator with test.
It always begin with (hyphen) followed by two-letter string and enclosed on either side by
whitespace.
Operator

Description

eq

Equal to

-ne

Not Equal to

-gt

Greater Than

-lt

Less Than

-ge

Greater than or equal to

-le

Less than or equal to

File Test : Test command has several options for checking the status of a file which listed below in
table.
Using this we can find out whether the specified file is an ordinary file or a directory or a
whether it grants read, write or execute permissions.
It also use with negates test !
Operator

TYBCA (SEM:5)

Description

PREPARED BY AMIT PATEL

Page 17

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS

Following script check inputted filename is regular file or not.


#!/bin/sh

We

can

use

test

and

interchangeably.
Echo Enter the file name:;
Read fname;
If test -f fname then
echo It is a file
Else
echo You enter is not a file
name
Fi

String Test :

There are following string operator used with expr to perform operation on string.

Operator

TYBCA (SEM:5)

Description

PREPARED BY AMIT PATEL

Page 18

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS

Following script check two string are equal or not.


#!/bin/sh
Str1 = Good Morning
Str2 = Good Bye
If test $str1 = $str2 ; then
echo $?
Since two string are assigned to variable str1 and str2, we have taken care to enclose the string
within a pair of double quotes.
Q

Shift Command

Shift transfer the contents of positional parameters to its immediate lower numbered one.
This is done as many time as the statement is called.
When called once, $2 becomes $1, $3 becomes $2, and so on.
For example 1: $ date
Wed Aug 19 04:10:30 IST 2015
$ echo $1 $2 $3
Wed Aug 19
For example 2:
$ Shift
$ echo $1 $2 $3
Aug 19 04:10:30

Explain SET utility

We have used the set command to set upto 9 words.

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 19

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
For Example: $ set Good morning Amit Patel. Hello, How are you. Hope you are fine.
$ echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11
Good morning Amit Patel. Hello, How are you. Hope Good0 Good1

Output:

If we observed the output of last two word Good0, Good1. This occurred in the output
because at a time we can access only 9 positional parameters. When we tried to refer $10 it
was interpreted by the shell as if you wanted to output the values $1 and 0. Same is true for
$11 as $1 and 1.
To access word after 9th word, we have to use shift.
For example:
$ Shift 9
$ Echo $1 $2 $3
Output: you are fine.
Q

Explain UMASK command.

Definition: User mask is a 3 digit octal system variable which is used initially set
permission for a directory of files.

Defined initially by system administrator when user account is created.

It contains the octal settings for the permissions that are to be removed from the default
when a directory or file is created.

You can change the settings by creating mask entry in you login file.

When new directory or file is created, the number in the mask is used to set the default
permission.

Default Permission :
For Directory: 777
For File: 666
MASK

TYBCA (SEM:5)

DIRECTORY PERMISSION

PREPARED BY AMIT PATEL

FILE PERMISSION

Page 20

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS

To display the current user mask settings, use the umask command with no argument.
$ umask
000

To set it, use the command with the new mask setting.
$ umask 022
$ umask
022

Explain at Command. (Mar/Apr-2015)

The AT command schedules commands and programs to run on a computer at a specified


time and date.
Syntax: at time date
It takes as its argument the time the job is to be executed and display the at> prompt.
Input has to be supplied from the standard input.
For Example:
$ at 14:08
at> empdetails.sh [Ctrl d ]
The job goes to the queue and at 2:08 PM today, the script file empdetails.sh will be
executed.
at doesnt indicate the name of script to be executed when it execute program.
at also offer key words now, noon, midnight, today and tomorrow It also accept + symbol
to act as an operator. The words that can be used with this operator include hours, days,
weeks, months and years.
For Example:

at 15, at 5pm, at noon, at 9am tomorrow, at 3:08pm + 1 day

You can schedule a job to be executed using relative time from now.
Syntax: $ at now + COUNT UNIT

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 21

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS

For example, following job will be execute 1 minute from now.


$ at now + 1 min
The above example will read the commands from stdin, and it will execute the job after a
minute. When you give something wrong in time format, you will get the error Garbled time.
at l is used to listed the job and at r is used to remove any job from list.
Q

Explain batch Command. (Mar/Apr-2015)

It is used to run multiple job without overloading the system.


The command doesnt take any arguments but uses an internal algorithm to determine the
execution time.
After typing batch at the command prompt, enter any number of commands one on each
line. When you are done press CTRL-d.
Syntax: $ batch
command1
....
commandN
CTRL-d
This allows you to schedule a number of commands at once without slowing down the
system by running them simultaneously. It will also continue to run the commands after you
logout usually sending email when the commands are finished.
For example, suppose you want to sort three large files. Instead of sorting them
simultaneously on background
$ sort bigfile1 &
$ sort bigfile2 &
$ sort bigfile3 &
Use the batch command to run them one at a time
$ batch
sort bigfile1
sort bigfile2

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 22

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
sort bigfile3
so that you do not slow down the computer as much.
When using batch you will typically want to use redirection to save output normally sent to
the screen to a file.
Difference between at and batch
at

batch

The AT command schedules commands and

It

is used to schedules

job for later

programs to run on a computer at a specified execution as soon as the system load


time and date
It takes as its argument the time the job is to

permits.
The command doesnt take any arguments

be executed

but uses an internal algorithm to determine


the execution time.

For Example:
$ at 14:08
at> empdetails.sh [Ctrl d ]
The job goes to the queue and at 2:08 PM
today, the script file empdetails.sh will be
executed.
Q

Explain crontab Command. (Mar/Apr-2015)

Once job submitted using this command have been executed, the job have been rescheduled
if they are to be carried out again.
For example: If we want to backup all our c program files at the end of the day then we do
it as follow
$ at 5 PM
cp *.c ./cbackup
We must remember to issue this command every morning to be able to take backup every
evening without failing.
To overcome this we have to use crontab command. The job can be carried out on a regular
basis using crontab command.

Crontab utility is an effective way to schedule a routine background job at a specific time
and/or day on an on-going basis.

Crontab format:

TYBCA (SEM:5)

MIN HOUR DOM MON DOW CMD

PREPARED BY AMIT PATEL

Page 23

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
Field

Description

Allowed Value

MIN

Minute field

0 to 59

HOUR

Hour field

0 to 23

DOM

Day of Month

1-31

MON

Month field

1-12

DOW

Day Of Week

0-6

CMD

Command

Any

command

to

be

executed.

Example: Let create a file which contain command we execute regularly but also the details
of date and time in a specific format we discussed previously.
Here we want to print message work Hard on 10:30 am on first day of every month.
Second command would mail the letter to user aa2 on 17th Nov. of every year.
$ cat > cmdfile
30
10
1
*
0
0
17
11
Crtl d
$ crontab cmdfile

*
*

echo Work Hard


mail aa2 < letter

The content of cmdfile are automatically transferred to the /user/spool/cron/crontab


directory where they are stored in a file which has the same name as your login name.
Following option we used with crontab command
crontab -e

Edit your crontab file, or create one if it doesn't already exist.

crontab -l

Display your crontab file.

crontab -r

Remove your crontab file.

crontab -v

Display the last time you edited your crontab file.

Explain NICE command.

Every running process in Unix has a priority assigned to it.


You can change the process priority using nice utility.
NICE command is used with & operator to reduce the priority of job.
Nice command will launch a process with an user defined scheduling priority.
The process scheduling priority range is from 1 to 19. We call this as nice value.

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 24

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
A nice value of 1 represents highest priority, and a nice value of 19 represent least priority for
a process.
Higher nice value implies a lower priority.
By default when a process starts, it gets the default priority of 0.
To Launch a Program with Less Priority : Instead of launching the program with the default priority, you can use nice command to
launch the process with a specific priority.
In this example, test.pl is launched with a nice value of 10.
$ nice -10 wc l manual &
Remember that -10 in the above command sets the priority of a process to 10. The in nice
command stands for the hypen.
Change the Priority with option n : The process priority can be adjusted with the help of -n option.
Increase the priority:

Q
A

$ nice -n -5 wc l manual &

Decrease the priority: $ nice -n 5 wc l manual &

Explain kill Command.(Sep-Oct 2012)

Use the kill command to send a signal to each process specified by a pid. The default signal

is SIGTERM (terminate the process).


We mostly use the kill command for terminating or killing a process. However we can also

use the kill command for running a stopped process.


Syntax:
kill [-s signal] pid
OR
kill l
PID means process id that kill command send a signal
-s signal means sent the specified signal to process.
-l means list all signals.

Kill command use one or more PID as its arguments.

For example:

Terminates the job having PID 105. To know the PID run ps command.

To kill multiple process, run following command

$ kill 105

$ kill 121 122 125

If all these process have the same parent, you may simply to kill the parent of all this
process to know the PPID.

To Killing the last background job:

The system variable $! store the PID of the last background job.

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 25

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS

So we can kill the last background job without using the ps command to find out PID
$ sort o emp.lst &
345
$ kill $!

By default, kill uses the SIGTERM signal (15) to terminate the process.

Process can be killed with the SIGKILL signal (9).

This signal cant be generated at the press of a key, we must use kill with signal name
preceded by the s option
$ kill s KILL 121

OR

$ kill -9 121

To kill your login shell : $ kill -9 $$

OR

$ kill s KILL 0

SIGNAL

USAGE

HUP (hang up)

INT (interrupt)

QUIT (quit)

ABRT (abort)

KILL (non-catchable, non-ignorable kill)

14

ALRM (alarm clock)

15

TERM (software termination signal)

The signal number 1 is a hangup signal. I recommended using 1 signal because it should
kill the process and it can save the buffer (if supported). For example if it is an editor, save
the buffer. This is the default if you do not specify a signal number. Signal number 9, a kill
signal, is the surest way to kill a process.

Explain ps command.

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 26

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
A

The ps command is used to display the attributes of a process. It has

knowledge of the

kernel built into it.


It reads through the kernel data structures or process table to fetch the process

characteristics.

By default, ps list out the processes associated with a user at that terminal

$ ps
PID
TTY
TIME
476
tty03
00:00:01
659
tty03
00:00:01
684
tty03
00:00:001
Each line show the pid, the

CMD
login
sh
ps
terminal with which the process is associated, the cumulative

processor time that has been consumed since the process has been started and process
name.
OPTION

DESCRIPTIONS

-f

Full listing showing the PPID of each process.

-e or A

All process including system and user process.

-u usr

Process of user usr only.

-a

Process of all user excluding processes not associated with terminal.

-l

Long listing showing memory related information.

-t term

Process running on terminal term

Example 1: Display a detailed listing of process also show parent of process.


$ ps -f
UID
PID PPID C
STIME
TTY
TIME CMD
root 476
1 0 17:51:58 tty03 00:00:01 /bin/login kumar
kumar 659 476 4 18:10:29 tty03 00:00:01 -sh
kumar 685 659 15 18:26:44 tty03 00:00:00 ps f

Description of all this column is listed in table


COLUMN

DESCRIPTION

UID

User ID that this process belongs to (the person running it).

PID

Process ID.

PPID

Parent process ID (the ID of the process that started it).

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 27

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS

CPU utilization of process.

STIME

Process start time.

TTY

Terminal type associated with the process

TIME

CPU time taken by the process.

CMD

The command that started this process.

Example 2: Display all user process but doesnt display the system process.
$ps a
PID TTY
662
705
1005
1056
1069

tty02
tty04
tty01
tty02
tty02

TIME CMD
00:00:00
00:00:00
00:00:00
00:00:00
00:00:00

ksh
sh
ksh
sort
ps

There are 3 user work here as terminal names displayed.

Example 3: Display the system process.


$ps e
PID
0
1
2

TTY

TIME CMD

?
?

00:00:00 sched
00:00:01 init
?
00:00:00 vhand
00:00:01 bdflush

Example 4: Display the process run by user om.


$ps u om

Explain Case Condition With Example In Shell. (Mar-Apr 2012).

You can use multiple if...elif statements to perform a multiway branch. However, this is not
always the best solution, especially when all of the branches depend on the value of a single
variable.

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 28

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS

Unix Shell supports case...esac statement which handles exactly this situation, and it does
so more efficiently than repeated if...elif statements.

Unix Shell's case...esac is very similar to switch...case statement we have in other


programming languages like C or C++

The basic syntax of the case...esac statement is to give an expression to evaluate and several
different statements to execute based on the value of the expression.

The interpreter checks each case against the value of the expression until a match is found.
If nothing matches, a default condition will be used.

Syntax:
case word in
pattern1)
Statement(s) to be executed if pattern1 matches
;;
pattern2)
Statement(s) to be executed if pattern2 matches
;;
pattern3)
Statement(s) to be executed if pattern3 matches
;;
esac

Here the string word is compared against every pattern until a match is found. The
statement(s) following the matching pattern executes. If no matches are found, the case
statement exits without performing any action.

There is no maximum number of patterns, but the minimum is one.

When statement(s) part executes, the command ;; indicates that program flow should jump
to the end of the entire case statement. This is similar to break in the C programming
language.
#!/bin/sh
FRUIT="kiwi"
case "$FRUIT" in
"apple") echo "Apple pie is quite tasty."

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 29

VIDYABHARTI TRUST COLLEGE OF BBA & BCA. UMRAKH


SUB: UNIX AND SHELL PROGRAMMING
IMPORTANT COMMANDS
;;
"banana") echo "I like banana nut bread."
;;
"kiwi") echo "New Zealand is famous for kiwi."
;;
esac
This will produce following result New Zealand is famous for kiwi.

TYBCA (SEM:5)

PREPARED BY AMIT PATEL

Page 30

Potrebbero piacerti anche