0% found this document useful (0 votes)
85 views69 pages

Stegnography

Rishav was taking the 5th semester subject of Unix and Shell Programming. The document contained sample questions from previous years' papers for this subject, divided into multiple choice questions and questions requiring longer answers. It defined key concepts like process creation in Unix, the difference between hard and soft links, and commands like kill, ps and chmod.

Uploaded by

Rishav Roy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views69 pages

Stegnography

Rishav was taking the 5th semester subject of Unix and Shell Programming. The document contained sample questions from previous years' papers for this subject, divided into multiple choice questions and questions requiring longer answers. It defined key concepts like process creation in Unix, the difference between hard and soft links, and commands like kill, ps and chmod.

Uploaded by

Rishav Roy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

NAME- RISHAV

ROLL NO – 31401219026

SEM- 5TH

SUBJECT- UNIX AND SHELL PROGRAMMING

(5 year solved question paper)

Unix and Shell Programming (2012)

Group - A

1. Multiple choice Type Questions)

i. To counting number of lines in a file which command is used.


Ans- wc
ii. In the core of the operating system is called
Ans- Kernel
iii. Which one works as interface between the user & the Kernel?
Ans- Shell
iv. To display an informative listing of the users…… is used.
Ans- who
v. To remove a directory ……… command is used.
Ans- rmdir
vi. To know your current directory, we use
Ans-pwd
vii. The UNIX command ‘cp ch * book’
Ans-Copies all files with three-character names that start with ch to the
directory book
viii. Suppose the current directory is/home/ user/ xyz/ prog. A possible command
to change to a directory/ home/ user/ abc / letter is
Ans- Cd.. / .. / abc / letter
ix. The UNIX command ‘rm -r project’ will
Ans- Recursively delete the directory project and all its sub-directories
x. The hidden file in UNIX
Ans- Have names starting with a dot
Group – B

1. How do you change File Access Permissions in Unix?


Ans-To change file Access Permissions, use the command ‘chmod’ (change
mode). The chmod command is used to manage file system access
permissions on Unix and Unix-like systems. These are three basic file
system permissions, or modes, to files and directories:
 Read(r) Permissions for a directory allows you to read the names of
the files contained in that directory with the ls command, but not to
use them.
 Write(w) permission for a directory allows you to create files in that
directory or to delete any file in the directory, regardless of the file
protection on the files themselves. It does not allow you to see the
files or use them without r and x directory permission. In other words,
write permission to a directory allows you to alter the contents of the
directory itself, but not to alter, except to remove, files in the directory
(which is controlled by the file’s permissions).
 Execute(x) permission allows you to list the contents of the directory.
Each mode can be applied to these classes:
 User(u): The user is the account that owns the file.
 Group(g): The group that owns the file may have other account on the
system as members.
 Other(o): The remaining class, other (sometimes referred to as world),
means all other accounts on the system.

2. What happens when you execute a program? Define Zombie.


Ans-When we execute a program on our Unix system, the system creates a
special environment for that program. This environment contains everything
for the system to run the program as is no other programs were running on
the system. Each process has process context, which is everything that is
unique about the state of the program you are currently running. Every time
we execute a program the Unix system does a fork, which performs a series
of operations to create a process context and then execute your program in
that context. The steps are:
 Allocate slot in process table (list of currently running processes).
 Assign unique id called as PID (Process ID).
 Process context is copied from the parent which requested to
spawn(create) new process.
 Return PID to parent, allowing him to monitor and control the new
process.

After forking the process, Unix Runs the program.

A zombie process is a process whose execution is completed but it still has an


entry in the process table. Zombie processes usually occur for child processes, as
the parent process still needs to read its child’s exit status. Once this is done using
the wait system call, the zombie process is eliminated from the process table. This
is known as reaping the zombie process.

3. Define hard link and soft link.

Ans-

Hard link Soft link


Files that are hard linked take the same Files that are soft linked take the
inode number. different inode number.
It cannot be used across file system It can be used across file systems

Data present in the original file will be Soft links only point to the file name, it
available in the hard links. does not retain data of the file.

Hard links are comparatively faster Soft links are comparatively slower.

Group – C

1. Describe mechanism of process creation. How a shell is created? What


are internal and external commands? Where are the security levels
available in UNIX?
Ans-A process in a Unix system is created by fork system call. Every
process except process 0 is created. The process that invokes the fork
system call is parent process and the newly created process is the child
process. Every process has one parent process but a parent can have many
child processes. The kernel identifies it process by its process identification
number (PID). Process 0 is a special process created “by hand” when the
system boots.
There are 3 distinct phases in mechanism of process creation and uses 3
system calls: fork (), exec () and wait ().

Fork (): Creates a child process. A new process is created because an


existing process creates an exact copy of itself. This child process has the
same environment as its parent but only the PID is different. This
procedure is known as forking.

exec (): After forking the process, the address space of the child process is
overwritten by the new process data. This is done through exec call to the
system. No new process is created over here. The PID & PPID remains
unchanged.

Wait (): The parent then executes wait system call to wait for the child
process to complete its execution.
The important attributes that are inherited by the child process from its
parent are: Real UID and GID, PGID, Nice value, Environment setting,
Current working directory, memory segments etc.
When the process dies it immediately moves to the zombie state and
remains in the state until the parent picks it up to exit status.

Steps for creating a shell:

• Create a file using a vi editor (or any other editor). Name script file with
extension.sh

• Start the script with #!/bin/sh

• Write some code.


• Save the script file as filename.sh

• For executing the script type bash filename.sh

Internal Commands: Commands which are built into the shell. For all the shell
built-in commands, execution of the same is fast in the sense that the shell
doesn’t have to search the given path for them in the path variable, and also no
process needs to be spawned for executing it.

Examples: source, cd, fg, etc.

External Commands: Commands which aren’t built into the shell. When an
external command has to be executed, the shell looks for its path given in the path
variable, and also a new process has to be spawned and the command gets
executed. They are usually located in/bin or /usr/bin. For example, when you
execute the “cat” command, which usually is at /usr/bin, the executable
/usr/bin/cat gets executed. Examples: ls, cat etc.

2. Define kill command. How you can kill the last background jobWhat
are the different environment variables in Unix? Explain ps command.
Ans-Kill command (located in bin/kill), is a built-in command which is used
to terminate processes manually. Kill command sends a signal to a process
which terminates the process. If the user doesn’t specify any signal which is
to be sent along with kill command, then default TERM signal is sent that
terminates the process.
To kill the last background job, the following command is used: $ kill $!The
system variable $! Stores the PID of the last background job. The other
method is first finding the PID using the ps command, then use kill
command to do the job.
Different environment variables in Unix are: -
 $user: Gives current user’s name.
 $PATH: Gives search path for commands.
 $PWD: Gives the path of present working directory.
 $HOME: Gives path of home directory
 $HOSTNAME: Gives name of the host
 $LANG: Gives the default system language
 $EDITOR: Gives default file editor
 $UID: Gives user ID of current user.
 $SHELL: Gives location of current user’s shell program

The ps command enables us to check the status of active processes on a system, as


well as display technical information about the processes. This data is useful for
administrative tasks such as determining how to set process priorities.

Depending on which options we use, the ps command reports the following


information:

 Current status of the process


 Process ID
 Parent process ID
 User ID
 Scheduling class
 Priority
 Address of the process
 Memory used
 CPU time used

3. a) what is quoting? What are three quote tokens?

Ans-Quoting is used to remove the special meaning of certain characters or words


to the shell. Quoting can be used to disable special treatment for special characters,
to prevent reserved words from being recognized as such, and to prevent parameter
expansion.

Three quote tokens are:

 Escape sequence (\): It protects the next character, except if it is a newline. If


a backslash precedes a newline, it prevents the newline from being
interpreted as a command separator, but the backslash-newline pair
disappears completely.
 Single quotes (‘…’): It protects everything (even backslashes, newlines, etc.)
except single quotes, until the next single quote.
 Double quotes (“…”): It protects everything except double quotes,
backslashes, dollar signs, and backquotes, until the next double quote.
b. What is regular expression? List out the components of it.

Ans-A regular expression (sometimes called a rational expression) is a sequence of


characters that defines a search pattern, mainly for use in pattern matching with
strings, or string matching, i.e. “find and replace” – like operations.It is a
generalized way to match patterns with sequence of characters. It is used in every
programming language like C++, Java and Python.

Components of Regular Expressions:

 Matching Fixed strings


 Matching Special Characters
 Matching Character Sets
 Specifying Groups and Fields
 Evaluating Occurrences
 Specifying Alternatives
 Matching Information from a table
 Capturing Multiple Lines
 Managing the scope of Analysis

c. What are egrep and fgrep? Give examples.

 Both egrep and fgrep are derived from the base grep command. The “egrep”
stands for “extended grep” while the fgrep stands for “fixed-string grep.”
 An egrep command is used to search for multiple patterns inside a file or
other kind of data repository while fgrep is used to look for strings.
 The term “egrep” is commonly expressed as “grep-e” while “fgrep” is
encoded as “grep-f”.

d. Differentiate between line editor and screen editor.

Ans-Line editor: A line editor is a basic type of computer-based text editor


whereby one line of a file can be edited at a time. Line editors were the precursor
to document editing software that is commonly used today. Line editors were used
before interactive video graphic screens were commonly available in computers.
The editing of a single line at a time was due to the unavailability of graphical
interface screens, cursors and memory, hence an average computer operator used a
teleprinter, whereby a printer was directly attached to keyboard and changes could
not be made once the text had been typed. Typically, the text is not entered into the
document until a complete line has been typed. The operator can view the typed
form once entered, but cannot go back to a previous line to edit it. While line
editors are no longer widely used, they are still utilized in some applications, such
as in shell scripts and MUD systems.

Screen editors: It is a computer software for editing text files using a textual or
graphical user interface which displays the content(text) in an easy to look at and
good view. i.e., it displays a portion of the opened file and updates it in real time.
By definition, all visual editors require a refreshable display and all editors with a
GUI are visual. In this type of editors, the user is able to see the cursor on the
screen and can make a copy, cut, paste operation easily. It is very easy to use
mouse pointer. Ex: vi, emacs, Notepad

4. Write short notes on any three of the following:

a) gzip and gunzip


Ans- gzip (GNU zip) is a free and open-source algorithm for file
compression. The software is overseen by the GNU project. In this context,
compression is the deliberate reduction in size of data to save storage space
or increase the data transfer rate. Gzip is most often used to compress web
pages on the server end for decompression in the browser. The format is
popular for compression of streaming media. Normally used to compress
individual files (such as the executable programs for installing software),
gzip can also be used to concatenate and compress several streams
simultaneously. Jean-Loup Gaily and Mark Adler developed gzip as a
replacement for compress, the format used in earlier versions of UNIX and
Linux. In comparison, gzip offers better compression than compress and,
unlike the earlier format, contains no proprietary algorithms. Gzip can also
be used with other operating systems, including Windows and Macintosh
Oses.
A gzip file has the extension .gz and contains a 10-byte header, optional
extra headers, a checksum and data indicating the original uncompressed file
size. Multiple files can be combined and compressed utility for Windows
and Macintosh, is based on an algorithm called deflate. Files compressed
using gzip can be unzipped with a program called gunzip.
Gunzip takes a list of files on its command line and replaces each file whose
name ends with .gz, -gz, .z, -z, _z or .Z and which begins with the correct
magic number with and uncompressed file without the original extension.
Gunzip also recognizes the special extensions .tgz and .taz as shorthand for
.tar.gz and .tar.Z respectively. When compressing, gzip used the .tgz
extension, if necessary, instead of truncating a file with a .tar extension.
Gunzip can currently decompress files created but gzip, zip, compress,
compress -H or pack. The detection of the input format is automatic. When
using the first two formats, gunzip checks a 32-bit CRC. For pack, gunzip
checks the uncompressed length. The standard compress format was not
designed to allow consistency checks. However, gunzip is sometimes able to
detect a bad. Z file. If you get an error when uncompressing a .Z file, do not
assume that the .Z file is correct simply because the standard uncompressed
does not complain. This generally means that the standard uncompressed
does not check its input, and happily generates garbage output. The SCO
compress -H format (lzh compression method) does not include a CRC but
also allows some consistency checks.

b) Awk

Ans- Awk is a scripting language used for manipulating data and generating
reports. The awk command programming language requires no compiling and
allows the user to use variables, numeric functions, string functions, and logical
operators. Awk is a utility that enables a programmer to write tiny but effective
programs in the form of statements that define text patterns that are to be searched
for in each line of a document and the action that is to be taken when a match is
found within a line. Awk is mostly used for pattern scanning and processing. It
searched one or more files to see if they contain lines that matches with the
specified patterns and then perform the associated actions. This command is named
by using the first letter of the name of three people who wrote the original version
of this command in 1977. Their names are Alfred Aho, Peter Weinberger, and
Brain Kernighan and they were from AT & T Bell Laboratories.

c) tar
Ans- The Linux ‘tar’ stands for tape archive, is used to create Archive and extract
the Archive files. Tar command is one of the important commands which provides
archiving functionality. We can use tar command to create compressed or
uncompressed Archive files and also maintain and modify them.

Syntax: tar [options] [archive-file] [file or directory to be archived]

Options:

 -c: Creates Archive


 -x: Extract the archive
 -f: creates archive with given filename
 -t: displays or lists in archived file
 -u: archives and adds to an existing archive file
 -v: Displays Verbose Information
 -A: Concatenates the archive files
 -z: sip, tells tar command that creates tar file using gzip
 -j: filter archive tar file using tbzip
 -w: Verify an archive file

An Archive file is a file that is composed of one or more files along with metadata.
Archive files are used to collect multiple data files together into a single file for
easier portability and storage, or simply to compress files to use less storage space.

Unix and Shell Programming (2013)

Group - A

1. Multiple choice Type Questions)

I. The UNIX command ‘a.out \& runs the program a.out


Ans.

II. The cal command is used to


Ans- show calendar
III. pwd command is used for
Ans- view the current working directory

IV. The command used to see the user processes is


Ans- ps

V. The available disk space under UNIX can be determined by


Ans- df

VI. In UNIX mounting means


Ans- copying all the files from one file system to another.

VII. The hidden file in UNIX

Ans- has names starting with dot

VIII. The chmod command in UNIX


Ans- changes the access permission of a file or directory

IX. Chown command in UNIX changes


Ans- ownership of a file

X. Base name student. 1st 1st -the output of this command is


Ans.

GROUP – B

1. What do you mean by Internal and External commands?

Ans -Internal Commands: Commands which are built into the shell. For
all the shell built-in commands, execution of the same is fast in the sense
that the shell doesn’t have to search the given path for them in the PATH
variable, and no process needs to be spawned for executing it.
Examples: source, cd, fg, etc.

External Commands: Commands which aren’t built into the shell. When


an external command must be executed, the shell looks for its path given in
the PATH variable, and a new process has to be spawned and the command
gets executed. They are usually located in /bin or /usr/bin. For example,
when you execute the “cat” command, which usually is at /usr/bin, the
executable /usr/bin/cat gets executed.
Examples: ls, cat etc.

2. What are the different runlevels in UNIX?

Ans-The standard LINUX kernel supports seven different runlevels:


Runlevel 0 – System halt i.e., the system can be safely powered off with no
activity.
Runlevel 1 – Single user mode.
Runlevel 2 – Multiple user mode with no NFS (network file system).
Runlevel 3 – Multiple user mode under the command line interface and not
under the graphical user interface.
Runlevel 4 – User-definable.
Runlevel 5 – Multiple user mode under GUI (graphical user interface) and
this is the standard runlevel for most of the LINUX based systems.
Runlevel 6 – Reboot which is used to restart the system.

3. What is the utility of ls and ls-a command?

Ans-ls command: - This command will show the full list or content of our
directory.

ls-a command: - This command will enlist the whole list of the current
directory including the hidden files.

4. What is i-node? Explain different attributes of i-node.


Ans-An i-node is a file data structure that stores information about any
Linux file except its name and data.
Each inode stores the attributes and disk block locations of the object's data.
File-system object attributes may include metadata (times of last change,
access, modification), as well as owner and permission data.

GROUP – C
1. A.Write the command you will give to set read, write, and execute
permissions, group member read and execute permission and others
only read permission for a file named zyx.txt.
Ans.-The command to set read, write, and execute permission is:
chmod rwx zyx.txt
The command to set read and execute permissions to group is:
chmod g+rx zyx.txt
The command to set only read permission to other is:
chmod o+r zyx.txt
B. State the importance of PID and PPID. Which process has the
maximum number of child processes?

Ans-Importance of PID: -
A process is given a unique number called process ID (PID) that identifies
that process to the system, when it is started. If we ever need to kill a
process, for an example, we can refer to it by its PID. As each PID is unique,
there is no ambiguity or risk of accidentally killing the wrong process
(unless we enter the wrong PID).

Importance of PPID: -
If any processes went wrong. We might try to quit a program only to find
that it has other intentions. The process might continue to run or use up
resources even though its interface closed. Sometimes, this leads to what is
called a zombie process, a process that is still running, but dead.

One effective way to kill a zombie process is to kill its parent process. This
involves using the ps command to discover the PPID of the zombie process
and then sending a kill signal to the parent. Of course, any other children of
the parent process will be killed as well.

C. Write a shell script to print all the odd numbers from 1 to 15.

Ans-echo "All odd numbers from 1 to 15:-"


i=1
while [ $i -le 15 ]
do
if [ `expr $i % 2` -ne 0 ]
then
echo $i
fi
i=`expr $i + 1`
done

2. A.Briefly explains the features of UNIX operating system.


Ans-The features of UNIX operating system are:

 Multiuser System: - Multiple users can log on to the system from


different terminals and run different jobs that share the resources of a
command terminal. It deals with the principle of time-sharing. Time-
sharing is done by a scheduler that divides the CPU time into several
segments also called a time slice, and each segment is assigned to
each user on a scheduled basis.

 Multitask System: - A UNIX operating system is a multitasking


operating system that allows you to initiate more than one task from
the same terminal so that one task is performed as a foreground and
the other task as a background process.

 Portability: -This feature makes the UNIX work on different


machines and platforms with the easy transfer of code to any
computer system. Since a significant portion of UNIX is written in C
language, and only a tiny portion is coded in assembly language for
specific hardware.

 File Security and Protection: - Being a multi-user system, UNIX


makes special consideration for file and system security. UNIX has
different levels of security using assigning username and password to
individual users ensuring the authentication, at the level providing file
access permission viz. read, write, and execute and lastly file
encryption to change the file into an unreadable format.
 Command Structure: UNIX commands are easy to understand and
simple to use. Example: "cp", mv etc. While working in the UNIX
environment, the UNIX commands are case-sensitive and are entered
in lower case.

 Communication: In UNIX, communication is an excellent feature


that enables the user to communicate worldwide. It supports various
communication facilities provided using the write command, mail
command, talk command, etc.

 Open Source: UNIX operating system is open source it means it is


freely available to all and is a community-based development project.

 Accounting: UNIX keeps an account of jobs created by the user. This


feature enhances the system performance in terms of CPU monitoring
and disk space checking. It allows you to keep an account of disk
space used by each user, and the disk space can be limited by each
other.

 UNIX Tools and Utilities: UNIX system provides various types of


tools and utilities facilities such as UNIX grep, sed and awk, etc.
Some of the general-purpose tools are compilers, interpreters, network
applications, etc.

B. Briefly state with syntax and example the following loops: while,
until, for.
Ans-
Syntax for while loop:
while command
do
Statement to be executed
Done

Example for while loop:


a=0
# -lt is less than operator
#Iterate the loop until a less than 10
while [ $a -lt 10 ]
do
# Print the values
echo $a

# increment the value

a=`expr $a + 1`
done

Syntax for until:

for var in word1 word2 ...wordn


do
Statement to be executed
Done

Example for until:


a=0
# -gt is greater than operator

#Iterate the loop until a is greater than 10


until [ $a -gt 10 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
done

Syntax for for:


until command
do
Statement to be executed until command is true
done

Example for for:

#Start of for loop


for a in 1 2 3 4 5 6 7 8 9 10
do
# if a is equal to 5 break the loop
if [ $a == 5 ]
then
break
fi
# Print the value
echo "Iteration no $a"
done

C. What do you understand by root directory?


Ans-The root directory is the directory on Unix-like operating systems that
contains all other directories and files on the system and which is designated
by a forward slash (/ ). The use of the word root in this context derives from
the fact that this directory is at the very top of the directory tree diagram A
filesystem is that commonly used to represent a file system hierarchy of
directories that is used to organize directories and files on a computer.

D. What is the importance of home directory?


Ans-The Linux home directory is a directory for a particular user of the
system and consists of individual files. It is also referred to as the login
directory. This is the first place that occurs after logging into a Linux
system. It is automatically created as "/home" for each user in the directory'.
It is a standard subdirectory of the root directory. The root directory contains
all other directories, subdirectories, and files on the system. It is denoted by
a forward slash (/).

3. A.What is a process?
Ans-A program/command when executed, a special instance is provided by
the system to the process. This instance consists of all the services/resources
that may be utilized by the process under execution.

B.Explain briefly foreground and background job execution in UNIX


system.
Ans-A foreground process is any command or task you run directly and wait
for it to complete. Some foreground processes show some type of user
interface that supports on-going user interaction, whereas others execute a
task and "freeze" the computer while it completes that task.
Unlike with a foreground process, the shell does not have to wait for a
background process to end before it can run more processes. Within the limit
of the amount of memory available, you can enter many background
commands one after another.

C. Explain with examples egrep and fgrep.


Ans-egrep command:
Egrep or grep -E is another version of grep or the Extended grep. This
version of grep is efficient and fast when it comes to searching for a regular
expression pattern as it treats meta-characters as is and doesn’t substitute
them as strings like in grep, and hence you are freed from the burden of
escaping them as in grep. It uses ERE or the Extended Regular Expression
set.
Fgrep command:
Fgrep or the fixed grep or grep -F is yet another version of grep which is fast
in searching when it comes to search for the entire string instead of regular
expression as it doesn’t recognize the regular expressions, neither any meta-
characters. For searching any direct string, this is the version of grep which
should be selected.

D. Write briefly on the following commands:


Ans-mount: This command is used to mount the file system found on a
device to big tree structure (Linux file system) rooted at ‘/ ‘.
umask: On Unix-like operating systems, the umask command returns, or
sets, the value of the system's file mode creation mask.

fsck: The fsck (File System Consistency Check) Linux utility checks file
systems for errors or outstanding issues. The tool is used to fix potential
errors and generate reports.

kill: The Kill command in UNIX or Linux operating system is used to send a
signal to the specified process or group.
4. A. How can you use ‘cat’ command to create a new file in UNIX?
Explain with example.
Ans-To create a new file, use the cat command followed by the redirection
operator (>) and the name of the file you want to create. Press Enter, type
the text and once you are done, press the ctrl+d to save the filE.

Example:
cat > file1.txt

B. Write a shell script to check whether a file is readable, writeable, or


executable.
Ans-echo -n "Enter file name: "

read file

# Find out if file has write permission or not

[ -w $file] && W="Write = yes" || W="Write = No"


 
# Find out if file has execute permission or not
[ -x $file] && X="Execute = yes" || X="Execute = No"
 
# Find out if file has read permission or not
[ -r $file] && R="Read = yes" || R="Read = No"
 
echo "$file permissions"
echo "$W"
echo "$R"
echo "$X"
C. Explain the shutdown command with at least two options.
Ans-The shutdown command in Linux is used to shut down the system in a safe
way. We can shut down the machine immediately or schedule a shutdown using
24-hour format. It brings the system down in a secure way. When the shutdown is
initiated, all logged-in users and processes are notified that the system is going
down, and no further logins are allowed.
Only root user can execute shutdown command.
The shutdown command with two options:

-r: Requests that the system be rebooted after it has been brought down.
-h: Requests that the system be either halted or powered off after it has been
brought down, with the choice as to which left up to the system.

D. Can ordinary user invoke shutdown command? Explain the significance of


run level 0, 1, 6.
Ans- Standard permissions do not allow regular users to shut
down a UNIX machine. Often it is useful to grant non-super users the ability to
shut down the server.

Runlevel 0: shuts down the system

Runlevel 1: single-user mode

Runlevel 6: reboots the system to restart it

5. Write short notes:

a) Cal: Cal command is a calendar command in Linux which is used to


see the calendar of a specific month or a whole year.

b) Touch: The touch command is a standard command used in


UNIX/Linux operating system which is used to create, change, and
modify timestamps of a file.

c) Basename: It takes a filename and prints the last component of the


filename.
UNIX external and internal commands:

a) Internal Commands: Commands which are built into the shell. For


all the shell built-in commands, execution of the same is fast in the
sense that the shell doesn’t have to search the given path for them in
the PATH variable, and no process needs to be spawned for
executing it.

b) External Commands: Commands which aren’t built into the shell.


When an external command must be executed, the shell looks for its
path given in the PATH variable, and a new process must be
spawned, and the command gets executed. They are usually located
in /bin or /usr/bin.

c) Who: The who command is used to get information about currently


logged in user on to system.

d) Mailx: Mailx is an intelligent mail processing system, which has


command syntax reminiscent of ed with lines replaced by messages.

Unix and Shell Programming (2014)

Group - A

`1. Answer all questions.

I. Double quotes protects all characters but permit


Ans- variable evaluation

II. In Linux , to echo a string and keep the cursor on the same line, you have to
use
Ans- the escape sequence

III. The user startup file for Bourne shell is stored in the home directory with the
name
Ans- .startup
IV. The Unix file system is characterized by
Ans- a hierarchical structure

V. Process switches from user modes to kernel modes is known as


Ans- context switching

VI. The password encryption file is stored in the file


Ans- /etc/passwd

VII. The alias command can be used in Unix to


Ans- assign the same name to two files

VIII. The directory file in Unix contains


Ans- only files names and only inode names

IX. The $! represents


Ans- exit status of last command

X. What will be the output of test $x – gt $y ( when x=7.2 and y = 7)


Ans- 0
Group - B

2. A. Explain the architecture of UNIX operating system.

Ans- UNIX has a graphical user interface similar to the Windows operating system
that makes it easy for navigation and a good supportive environment. The internal
design view of this operating system can be known from its architecture.

The architecture of this operating system is four layered. It consists of Hardware,


Kernel, System Call interface (shell) and application libraries/tools, utilities; etc
the kernel controls the hardware of the computer and resides at the core of the
architecture. System calls acts as the interface between the kernel and other
libraries. These libraries include general functions and built on top of the system
calls. Shell is a special application that provides an interface to the other
applications of the architecture.
B. what do you mean by positional parameters in shell programming?

Ans- A positional parameter is a parameter denoted by one or more digits, other


than the single digit 0. Positional parameters are assigned from the shell’s
arguments when it is invoked, and may be reassigned using the set builtin
command. Positional parameter N may be referenced as ${N}, or as $N when N
consists of a single digit. Positional parameters may not be assigned to with
assignment statements. The set and shift builtins’ are used to set and unset them
(see Shell Builtin Commands). The positional parameters are temporarily replaced
when a shell function is executed (see Shell Functions).When a positional
parameter consisting of more than a single digit is expanded, it must be enclosed in
braces.

3. A. What is umask? How can file permission be defined with it?

Ans- The umask is a four-digit octal number that UNIX uses to determine the file
permission for newly created files. Every process has its own umask, inherited
from its parent process. The umask specifies the permissions you do not want
given by default to newly created files and directories. umask works by doing a
bitwise AND with the bitwise complement of the umask. Bits that are set in the
umask correspond to permissions that are not automatically assigned to newly
created files.

B. what is touch command? Explain with an example?

Ans- The touch command is a standard command used in UNIX operating system
which is used to create, change and modify timestamps of a file.it is used to create
a file without any content. The file created using touch command is empty. This
command can be used when the user doesn’t have data to store at the time of file
creation.

For e.g - initially, we are in home directory and this can be checked using the pwd
command. Checking the existing files using command ls and then long listing
command (ll) is used to gather more details about existing files. You can create a
single file at a time using touch command.

Syntax: touch file_name


4. What is inode in UNIX file system? List down the main field consisting a
disk inode. What is the difference between disk inode and in-core-inode?

Ans- The inode is a data structure in a Unix-style file system that describes a file-
system object such as a file or a directory. Each inode stores the attributes and
disk block locations of the object's data. File-system object attributes may include
metadata (times of last change, access, modification), as well as owner and
permission data. It describes a file or a folder. It includes things like the owner,
the group, permissions, file size, created/modified/access timestamps, and more.

Disk inode - The inode is a data structure that describes a file. The inode is
actually a structure on file system. To open a file, the kernel copies the inode into
memory. As the file changes, the in-core inode is updated usually more often than
the on-disk copy. And the in-core inode has a few extra fields that are only
needed while the file is opened.

In-core-inode - In - core inode refers to inode which is present in the main


memory. The kernel uses it whenever a process wants to manipulate a file in the
secondary memory. It is a dynamic entity. On- disk inode is a static entity & is
present only in the Secondary memory

5. What is grep and sed command? Describe their function with example.

Ans- sed command- SED command in UNIX is stands for stream editor and it
can perform lots of function on file like, searching, find and replace insertion or
deletion. Though most common use of SED command in UNIX is for substitution
or for find and replace. By using SED you can edit files even without opening it,
which is much quicker way to find and replace something in file, than first
opening that file in VI Editor and then changing it. For e.g. - Sed command is
mostly used to replace the text in a file. The below simple sed command replaces
the word “unix” with “Linux” in the file.

$sed’s/unix/linux/' bcafile.txt

Input:

UNIX is great os. UNIX is open source. UNIX is free os.


Learn operating system.

UNIX linux which one you choose.

Output:

Linux is great os. Linux is open source. Linux is free os.

Learn operating system.

Linux Linux which one you choose.

Grep command- The grep filter searches a file for a particular pattern of
characters, and displays all lines that contain that pattern. The pattern that is
searched in the file is referred to as the regular expression. For e.g.-Grep displays
the entire line which has the matched string. We can make the grep to display
only the matched string by using the -o option.

$ grep -o "unix" geekfile.txt

Output:

UNIX
UNIX
UNIX
UNIX
UNIX
UNIX

Group – C

7. Explain $#, $*, $@ special parameters of shell.

Ans- $#- it is quite a special bash parameter and it expands to a number of


positional parameters in decimal.

$*- Expands to the positional parameters, starting from one. When the expansion
is not within double quotes, each positional parameter expands to a separate
word. In contexts where it is performed, those words are subject to further word
splitting and filename expansion. When the expansion occurs within double
quotes, it expands to a single word with the value of each parameter separated by
the first character of the IFS special variable.

$@- Expands to the positional parameters, starting from one. In contexts where
word splitting is performed, this expands each positional parameter to a separate
word; if not within double quotes, these words are subject to word splitting. In
contexts where word splitting is not performed, this expands to a single word
with each positional parameter separated by a space. When the expansion occurs
within double quotes, and word splitting is performed, each parameter expands to
a separate word.

8. A. What is function of test command?

Ans- The test command is used to check file types and compare values. Test is
used in conditional execution. It is also used for:

File attributes comparisons

Perform string comparisons.

B. how can you make out whether two files are copied or linked?

Ans- Use the long listing functions of 'ls'. You will see a link count > 1 and a
reference to where the file is linked to if it is a link. Without a link it is a copy.

C. Describe the two main functions of Init what is the significance of run
level 0, 1, and 6?

Ans- Init is the parent of all processes, executed by the kernel during the booting of
a system. Its principle role is to create processes from a script stored in the file.

It usually has entries which cause Init to spawn Getty’s on each line that users
can log in. It controls autonomous processes required by any particular system.

0 - To halt the system


1 - To get the system down into single user mode
6 - To reboot the system
9. Describe the layered architecture of UNIX operating system. Write down
the services provided by the UNIX kernel the context of a process.

Ans- The UNIX operating system consists of a kernel layer, a shell layer and a
utilities and applications layer. These three layers create a portable, multiuser,
multitasking operating system. There are multiple versions of the OS, but every
version has the exact same structure. UNIX is used by programmers, businesses,
universities and governments because of its stability and its ability to perform
many tasks simultaneously.
The UNIX kernel is the central core of the operating system. It provides an
interface to the hardware devices as well as to process, memory, and I/O
management. The kernel manages requests from users via system calls that
switch the process from user space to kernel space each time a user process
makes a system call such as read (), fork (), exec (),open (), and so on.

10. A. What is the difference between process run with & and run with nohup?
Ans- The nohup command is a signal-masking utility. It’s used to accept HUP
(hang up) signals that can be sent to a process by the kernel and block them. This
command is helpful when a user wants to start a long-running application and
then log out, or close the window in which the process was initiated. Either of
these actions normally prompts the kernel to hang up on the application, but a
nohup wrapper will allow the process to continue.

The & relates to job control in an active shell. It’s helpful for running a process in
a session in the background, so that the user can do additional work in the session
concurrently.

B. What do you mean by job scheduling in UNIX? Explain with the help of
proper example.
Ans- Job scheduling is the process of allocating system resources to many
different tasks by an operating system The system handles prioritized job queues
that are awaiting CPU time and it should determine which job to be taken from
which queue and the amount of time to be allocated for the job. This type of
scheduling makes sure that all jobs are carried out fairly and on time.
Most OSs like UNIX, Windows, etc., includes standard job-scheduling abilities.
For e.g- at Tuesday +2 hours /home/amit/scripts
Press: Ctrl + D
The job will run on each Tuesday after 2 hours of current time of scheduling.

C. Explain the difference between 1) ls-l and Is-It .


Ans-
ls-l Is-It
Command used to display long listing Command used to display long listing
of files and directories in the current of files and directories in the current
directory with their seven attributes directory with their seven attributes
including permissions, links, owner, including permissions, links, owner,
group owner, size, last modification group owner, size, last modification
time and filename. Files and directories time and filename but Files and
are sorted in ASCII collating sequence. directories are sorted by last
modification time.

D. Describe init and getty process for logging the system.


Ans- n Unix-based computer operating systems, init (short for initialization) are
the first process started during booting of the computer system. Init is a daemon
process that continues running until the system is shut down. It is the direct or
indirect ancestor of all other processes and automatically adopts all orphaned
processes. Init is started by the kernel during the booting process; a kernel panic
will occur if the kernel is unable to start it. Init is typically assigned process
identifier.

getty, is a UNIX program running on a host computer that manages physical or


virtual terminals (TTYs). When it detects a connection, it prompts for a username
and runs the 'login' program to authenticate the user.
Originally, on traditional UNIX systems, getty handled connections to serial
terminals (often Teletype machines) connected to a host computer. The tty part of
the name stands for Teletype, but has come to mean any type of text terminal.
One getty process serves one terminal. In some systems, for example, Solaris,
getty was replaced by ttymon.
Personal computers running Unix-like operating systems, even if they do not
provide any remote login services, may still use getty as a means of logging in on
a local virtual console. Instead of the login program, getty may also be set up by
the system administrator to run any other program, for example pppd (point-to-
point protocol daemon) to provide a dial-up Internet connection

11. A. write a shell script to print all prime numbers between 1 to n (must be
input by user).

Ans- clear
echo "enter the range"
read n
echo "the prime no are:"
m=2
while [ $m -le $n ] do
i=2 flag=0
while [ $i -le `expr $m / 2` ] do
if [ `expr $m % $i` -eq 0 ] then
flag=1 break fi
i=`expr $i + 1`
done
if [ $flag -eq 0 ]
then echo $m fi
m=`expr $m + 1`
done

12. A. write shorts notes on any three of the following:

a) Interprocess communication- The traditional method of interprocess


communication in UNIX is the pipe. Unfortunately, pipes can have framing
problems. Messages can become intermingled by multiple writers or torn
apart by multiple readers.IPC messages mimic the reading and writing of
files. They are easier to use than pipes when more than two processes must
communicate by using a single medium. The IPC shared semaphore facility
provides process synchronization. Shared memory is the fastest form of
interprocess communication. The main advantage of shared memory is that
the copying of message data is eliminated. The usual mechanism for
synchronizing shared memory access is semaphores.
b) Unix file system- Unix file system is a logical method of organizing and
storing large amounts of information in a way that makes it easy to manage.
A file is a smallest unit in which the information is stored. Unix file system
has several important features. All data in Unix is organized into files. All
files are organized into directories. These directories are organized into a
tree-like structure called the file system.

c) Vi editor - Vi or the Visual Editor is the default text editor that comes with
most Linux systems. It is a Terminal-based text editor that users need to
learn, essentially when more user-friendly text editors are not available on
the system. Some other reasons to use Vi include:

 VI is available on almost all operating systems.

 A smart range of shortcuts that comprise of short keystrokes.

 You can use Vi as an excellent html editor.

d) Filter in UNIX - Filters are programs that take plain text(either stored in a
file or produced by another program) as standard input, transforms it into a
meaningful format, and then returns it as standard output. Linux has a
number of filters. Some of the most commonly used filters are explained
below:

cat: Displays the text of the file line by line.

Unix and Shell Programming (2015)

Group – A

1. Answer any ten questions.

I. The ‘logout’ built in command is used to

Ans- to exit the current shell


II. The command ‘umask -S’
Ans- print the current mask using symbolic notation

III. Which option of the kill command sends the given signal name to the
specified process?

Ans-S

IV. Which command puts a script to sleep until a signal is received?

Ans-Suspend

V. The command ‘ulimit’

Ans-both A and B

VI. Which command wait for the specified process to complete and return the
exit status?

Ans-wait

VII. Which command prints the accumulated user and system times fro processes
run from the shell?

Ans- times

VIII. The expression expr -9% 2 evaluates to

Ans -1

IX. Create a new file “new.text” that is a concatenation of “file1.text” and


file2.text”

Ans-cat file1.text file2.text>new.text

X. Which shell offers a command history feature?

Ans- bourne shell


XI. Which command is used to remove a print job from the print queue?

Ans- Iprm

XII. ‘chown’ command changes the

Ans- home directory of a user

GROUP - B

1. Differentiate between multi programming and multi taksing. What are


the differences between relative and absolute path?

Ans-

Multi-Programming Multi-Tasking
Multiprogramming is implemented by Multitasking is implemented by using the
using the concept of context switching concept of time sharing.
In multiprogramming, to execute the In multirasking, to allot a task we need
processes, only one CPU is used. Multiple CPU’s.
Multiprogramming requires more times Multitasking requires less time to execute
to execute processes. processes.

Relative Path Absolute Path


It specifies the location from the root It is related to the location from current
directory. directory.
Beings with a delimiting character. Never begin with a delimiting character.
Content from other domains. Content from the same domain.

2. What is daemon process? What is the difference between cd and cd..?

Ans-A daemon is a type of programming on Unix-like operating systems


that runs unobtrusively in the background, rather that under the direct
control of a use, waiting to be activated by the occurrence of a specific
event or condition. A daemon is a long-running background process that
answers requests for services. The team orignated with Unix, but most
operating systems use daemons in some form or another. In Unix, the names
of daemons conventionally end in “d”. Some examples nclde inetd, httpd,
nfsd, sshd, named, and lpd.

The difference is that cd is a single command, no arguments. If there are no


arguments, cd will go to your home folder by default. Now, by contrast..
always means “one directory up” or parent directory. So when you do cd.. It
will go up one level. And this is always true, with exception of / folder,
because there is nowhere else to go. Here’s demo:

$pwd

/etc

$cd..

$cd..

$pwd

Using this knowledge in practice where are the two commands useful? Cd
will jump back to your home directory, which is the same as doing cd~ or
doing cd $HOME. This means that if you are somewhere very very deep in
directory tree, you can quickly and easily go back to home directory. Here’s
an example:

$pwd

/sys/class/block/sda1/holders

$cd
$pwd

/home/xieerqi

With .. we can also do cool things. Let’s say I am in


/sys/class/block/sda1/holders folder and I want to quickly go to up 3 levels.
So we can do this:

$pwd

/sys/class/block/sda1/holders

$cd ../../ ../

/sys/class/
3. What are the different ways of using chmod?
Ans- The chmod command changes the access permissions of files and
folders. The chmod command, like other commands, can be executed from
the command line or through a script file.
Command Syntax
This is the proper syntax when the chmod command:

chmod [options] mode[,mode] file1 [file2...]


The following are the usual options used with chmod:
1. -f, --silent, --quiet: Suppresses most error messages.
2. -v, --verbose: Outputs a diagnostic for every file processed.
3. -c, --changes: Like verbose but reports only when a change is made.
4. -R, --recursive: Changes files and directories recursively.
5. --help: Displays help and exits.
6. --version: Outputs version information and exits.

Below is a list of numerical permissions that can be set for the user, group,
and everyone else on the computer. Next to the number is the read, write,
and execute letter equivalent.

1. 7,rwx: Read, write , and execute


2. 6, rw: read and write
3. 5, r-w: read and execute
4. 4, r--: read-only
5. 3, -wx: write and execute
6. 2, -w- : write only
7. 1, --x: execute only
8. 0, ---: None

Command Examples
To change the permissions of the file participants so that everybody has full
access to it, enter:

chmod 777 participants

The first 7 sets the permission for the user, the second 7 sets the permissions
for the group, and the third 7 sets the permissions for everybody else.
If you want to be the only one who can access it, use:

chmod 700 participants

To give yourself and your group members full access, enter:

chmod 770 particicpants

If you want to keep full access for yourself, but want to keep other people
from modifying the file, use:

chmod 755 participants

The following uses the letters from above to change the permissions of
participants so that the owner can read and write to the file, but it doesn’t
change permissions for anyone else:

chmod u=rw participants

4. Draw the UNIX architecture. What are the different parts of it?
Ans-

The kernel and shell are the heart and


soul of the operating system.
The kernel ingests user input via the shell and accesses the hardware to perform
things like memory allocation and file storage.

The shell is an interface that interprets the command line input and calls the
necessary programs to do the work. The commands that you enter are programs
themselves, so once the work is done, the command line will return to a prompt
and await further input.

There are several different shells, and syntax and shortcuts vary between them. For
example, the "csh" shell listed in the image above is called "C shell" and has
syntax similar to the C programming language. All shells support similar basic
functions.

One example of how the shell and kernel work together is copying a file. If you
want to copy a file named "file1" and name the copy "file2", you would enter "cp
file1 file2" at the command line. The shell will search for the program "cp" and
then tell the kernel to run that program on "file 1" and name the output "file 2".
When the copying is finished, the shell returns you to the prompt and awaits more
commands

5. What is i-node? What does it contain?

Ans- An inode (short for “index node”) is a data structure Linux uses to
store information about a file. Each node has a unique ID that identifies an
individual file or other object in the Linux file system.

Inode contain the following information:

File type – file, folder, executable program etc.

File size

Time stamp – creation, access, modification times

File permissions – read, write, execute.

Access control list – permissions for special users/groups


File protection flags

File location – directory path where the file is stored

link count – number of hardlinks to the inode

additional file metadata

File pointer – addresses of the storage blocks that store the file contents.
6. What is filter? Describe the function of any two filters.
Ans- Filters are programs that take plain text(either stored in a file or
produced by another program) as standard input, transforms it into a
meaningful format, and then returns it as standard output. Linux has a
number of filters. Some of the most commonly used filters are explained
below:

1. cat : Displays the text of the file line by line. 


Syntax:  
cat [path]

2. head : Displays the first n lines of the specified text files. If the number of
lines is not specified then by default prints first 10 lines. 
Syntax:
head [-number_of_lines_to_print] [path]

GROUP – C
1. A. Write a shell program to find prime numbers between 1 to n.
Ans-
echo "enter the range"
read n
echo "the prime no are:"
m=2
while [ $m -le $n ] do
i=2 flag=0
while [ $i -le `expr $m / 2` ] do
if [ `expr $m % $i` -eq 0 ] then
flag=1 break fi
i=`expr $i + 1`
done
if [ $flag -eq 0 ]
then echo $m fi
m=`expr $m + 1`
done

B. What do you understand by PATH variable? How does the kernel


access file?
Ans- The PATH variable is an environment variable that contains an
ordered list of paths that Linux will search for executables when running a
command. Using these paths means that we do not have to specify an
absolute path when running a command.
For example, if we want to print Hello, world!, the command echo can be
used rather than /bin/echo so long as /bin is in PATH:

echo "Hello, world!"

Linux traverses the colon-separated paths in order until finding an


executable. Thus, Linux uses the first path if two paths contain the desired
executable.

The kernel accesses the file through the file system independent vnode
interface which points to an associated inode structure if the file is stored in
a Unix file system. On a Unix File System, the first 12 entries address data
block locations directly on the storage device.

C. What is unique command? Explain with example.


Ans-The uniq command in Linux is a command line utility that reports or
filters out the repeated lines in a file.
In simple words, uniq is the tool that helps to detect the adjacent duplicate
lines and also deletes the duplicate lines. uniq filters out the adjacent
matching lines from the input file(that is required as an argument) and writes
the filtered data to the output file . 
Syntax of uniq Command :
//...syntax of uniq...//
$uniq [OPTION] [INPUT[OUTPUT]]
Example:
//displaying contents of kt.txt/
$cat kt.txt
I love music.
I love music.
I love music.

I love music of Kartik.


I love music of Kartik.
Thanks.

Now, as we can see that the above file contains multiple duplicate lines.
Now, lets’s use uniq command to remove them:

//...using uniq command.../


$uniq kt.txt
I love music.

I love music of Kartik.

Thanks.

/* with the use of uniq all


the repeated lines are removed*/

As you can see that we just used the name of input file in the above uniq
example and as we didn’t use any output file to store the produced output,
the uniq command displayed the filtered output on the standard output with
all the duplicate lines removed.

2. A. Describe the log in process briefly.


Ans-The following step-by-step description shows what happens each time a
user logs in to a UNIX computer system.
Users enter their username.
User enters their password.
The operating system confirms your name and password.
A "shell" is created for you based on your entry in the "/etc/passwd" file (in
small businesses, this is usually a Bourne Shell).
You are "placed" in your "home"directory.
Startup information is read from the file named "/etc/profile". This file is
known as the system login file. When every user logs in, they read the
information in this file.
Additional information is read from the file named ".profile" that is located
in your "home" directory. This file is known as your personal login file.
(This is the file that usually contains the "menu" program.)

(b) Describe the ps -f command in detail.


Ans- The ps command enables you to check the status of active processes on
a system, as well as display technical information about the processes. This
data is useful for such administrative tasks as determining how to set process
priorities.
Depending on which options you use, the ps command reports the following
information:
Current status of the process
Process ID
Parent process ID
User ID
Scheduling class
Priority
Address of the process
Memory used
CPU time used
The following table describes some fields that are reported by the ps
command. Which fields are displayed depend on which option you choose.

Field  Description 

UID The effective user ID of the process's owner. 

PID The process ID. 


Field  Description 

PPID The parent process ID. 

C The processor utilization for scheduling. This field is not displayed when
the -c option is used.

CLS The scheduling class to which the process belongs: real-time, system, or
timesharing. This field is included only with the -c option.

PRI The kernel thread's scheduling priority. Higher numbers indicate a higher
priority. 

NI The process's nice number, which contributes to its scheduling priority.


Making a process “nicer” means lowering its priority.

ADDR The address of the proc structure.

SZ The virtual address size of the process. 

WCH The address of an event or lock for which the process is sleeping.  
AN

STIM The starting time of the process (in hours, minutes, and seconds). 
E

TTY The terminal from which the process (or its parent) was started. A
question mark indicates that there is no controlling terminal. 

TIME The total amount of CPU time used by the process since it began. 
Field  Description 

(c) Decribe the mode of vi editor.


Ans: The default editor that comes with the UNIX operating system is called
vi (visual editor). Using vi editor, we can edit an existing file or create a new
file from scratch. we can also use this editor to just read a text file.
Syntax:
vi filename

Command Mode: When vi starts up, it is in Command Mode. This mode is


where vi interprets any characters we type as commands and thus does not
display them in the window. This mode allows us to move through a file,
and to delete, copy, or paste a piece of text.
To enter into Command Mode from any other mode, it requires pressing the
[Esc] key. If we press [Esc] when we are already in Command Mode, then vi
will beep or flash the screen.

Insert mode: This mode enables you to insert text into the file. Everything
that’s typed in this mode is interpreted as input and finally, it is put in the
file. The vi always starts in command mode. To enter text, you must be in
insert mode. To come in insert mode you simply type i. To get out of insert
mode, press the Esc key, which will put you back into command mode.

Last Line Mode(Escape Mode):Line Mode is invoked by typing a colon


[:], while vi is in Command Mode. The cursor will jump to the last line of
the screen and vi will wait for a command. This mode enables you to
perform tasks such as saving files, executing commands.

3. A. Write a shell program to generate fibonaci series.


Ans- Program for Fibonacci
## Series
# Static input fo N
N=6
# First Number of the

# Fibonacci Series

a=0

# Second Number of the

# Fibonacci Series

b=1

echo "The Fibonacci series is : "

for (( i=0; i<N; i++ ))

do

echo -n "$a "

fn=$((a + b))

a=$b

b=$fn

done

# End of for loop

4. Write short notes on any three of the following :

a.Soft link and Hard link

Ans: Hard Link


Each hard linked file is assigned the same Inode value as the original,
therefore they reference the same physical file location. Hard links more
flexible and remain linked even if the original or linked files are moved
throughout the file system, although hard links are unable to cross different
file systems.

Soft Link-A soft link is similar to the file shortcut feature which is used in
Windows Operating systems. Each soft linked file contains a separate Inode
value that points to the original file. As similar to hard links, any changes to
the data in either file is reflected in the other. Soft links can be linked across
different file systems, although if the original file is deleted or moved, the
soft linked file will not work

b.Background job execution

Ans: Background job is a non-interactive process that runs behind the


normal interactive operations. They run in parallel and do not disturb
interactive (foreground jobs) processes and operations.It is scheduled from
SM36. You can analyze it from SM37 by viewing its job log.
Unix and Shell Programming (2017)

Group – A

1. Choose the correct alternatives for the following :

I. $$ represents
Ans- PID of the current shell.

II. A file abc contains four columns , Roll No, Name, Marks and Grades. What
will be the output, if we apply the following command sort -n -r + -3 abc It
will.
Ans- numeric sorts in reverse order of the file abc on third column.

III. Which of the following is the command for searching a pattern?


Ans- grep

IV. Each entry in inode table is of size.


Ans- 64 bytes

V. The password of Unix System is stored in the file.


Ans- /etc/passwd

VI. The hidden file in UNIX.


Ans- Has names starting with a dot.

VII. What is the standard file descriptor of the standard output?


Ans-1

VIII. To display the unique lines after sorting we use


Ans-sort -u -o file1 file2

IX. The command cut-f2, 8 – d”: “file 1 would output


Ans- none of these

X. In UNIX, mounting a file system means


Ans- Providing a link to the file system to be mounted so that it appears as a
local sub-directory.

XI. The UNIX command ‘rm -r project’ will


Ans- Recursively deletes the directory project and all its sub – directories

Group – B
1. What is relative and absolute permission? Explain with example. Where
the GID (both the number and name) is stored?
Ans-Relative permission is a permission where it changes the permission
specified in command and leaves other permission unchanged. In relative
mode we signify what we want to add or remove and to whom with single
letter abbreviations for example r for read, w for write, x for execute.
+(plus) means assign permission, -(minus) means remove permission, =
(equals to) means absolute permission for all.
syntax: chmod categorization permission filename
example chmod u+r file.txt
Absolute permission is a permission signified by numbers which have
special meanings. It uses numbers to represent file permissions. When we
change permissions by using the absolute mode, represent permissions for
each triplet by an octal mode number. It is specified by setting all nine
permission bits explicitly. In the chmod we used three octal number.
The GID (both the number and name) is stored in /etc/passwd and /etc/group.

2. Write a shell script to check weather an integer is prime or not.


Ans- clear
echo “Enter a number”
read number
i=2
flag=0
while test $i -le `expr $number / 2`
do
if test `expr $number % $i` -eq 0
then
flag=1
fi
i=`expr $i + 1`
done if test $flag -eq 1
then
echo "The number is Not Prime"
else
echo "The number is Prime"
Fi

4. What is i-node? What does it contain?


Ans-An inode is a data structure in UNIX operating systems that contains
important information pertaining to files within a file system. When a file
system is created in UNIX, a set amount of inode is created, as well.
The inode contains all the administrative data needed to read a file. Every
file’s metadata is stored in inodes in a table structure. Inodes store
information about files and directories or folders, such as file ownership,
access mode like read, write, execute permissions, and file type. On many
older file system implementations, the maximum number of inodes is fixed
at file system creation, limiting the maximum number of files the file system
can hold. When using a program that refers to a file by name, the system will
look in the directory entry file where it exists to pull up the corresponding
inode. This gives your system the file data and information it needs to
perform processes or operations.

5. What does the fork system call do? What does it return?
Ans -The fork system call is used to create new processes. The newly
created process is the child process. The process which calls fork and creates
a new process is the parent process. The child and parent processes are
executed concurrently.
But the child and parent processes reside on different memory spaces. These
memory spaces have same content and whatever operation is performed by
one process will not affect the other process.
When the child processes are created; now both the processes will have the
same Program Counter, so both of these processes will point to the same
next instruction. The files opened by the parent process will be the same for
child process.

Fork system call returns 0 in the child process and positive integer in the
parent process. Here, two outputs are possible because the parent process
and child process are running concurrently.

6. Write short notes on the following UNIX commands with different


Options.
A) Date
Ans- Date command is used to display the system date and time. date
command is also used to set date and time of the system. By default, the date
command displays the date in the time zone on which UNIX or LINUX
operating system is configured. We must be the super-user or root user to
change the date and time.
Syntax:
date [OPTION]... [+FORMAT]
$date -u
$date --date="2/02/2010"
$date --date="Feb 2 2010"

b) Who
Ans- who command is used to find out the following information the time of
last system boot, Current run level of the system, List of logged in users and
more. The who command is used to get information about currently logged
in user on to system. The who command displays the following information
for each user currently logged in to the system if no option is provided Login
name of the users, Terminal line numbers, Login time of the users into
system, Remote host name of the user

Syntax: $who [options] [filename]

c) Passwd
Ans -passwd command in Linux is used to change the user account
passwords. The root user reserves the privilege to change the password for
any user on the system, while a normal user can only change the account
password for his or her own account.
Syntax:
Passwd [options] [username]

Group – C

7. A) briefly explain the features of UNIX Operating System?


Ans- Unix is an operating system, so it has all the features that the OS must-have.
UNIX also looks at a few things in a different way than other OS. Features of
UNIX are listed are:
1. Multiuser System:
Unix provides multiple programs to run and compete for the attention of the
CPU. This happens in 2 ways:
• Multiple users running multiple jobs
• Single user running multiple jobs
In UNIX, resources are shared between all the users, so-called a multi-user
system. For doing so, computer give a time slice to each user. So, at any instant
of time, only one user is served but the switching is so fast that it gives an illusion
that all the users are served simultaneously.

2. Multitask System:
A single user may run multiple tasks concurrently. Example: Editing a file,
printing another on the printer & sending email to a person and browsing the net
too at the same time. The Kernel is designed to handle user’s multiple needs.
The important thing here is that only one job can be seen running in the
foreground, the rest all seems to run in the background. Users can switch between
them; terminate/suspend any of the jobs.

3. The Building-Block Approach:


The Unix developers thought about keeping small commands for every kind of
work. So, Unix has so many commands, each of which performs one simple job
only. We can use 2 commands by using pipes (‘|’). Example : $ ls | wc Here, |
(pipe) connects 2 commands to create a pipeline. This command counts the
number of files in the directory. These types of connected commands that can
filter/manipulate data in other ways are called filters.

4. The UNIX Toolkit:


Unix has a kernel, but the kernel alone can’t do much that could help the user. So,
we need to use the host of applications that usually come along with the UNIX
systems. The applications are quite diversified. General-purpose tools, text
manipulation utilities, compilers and interpreters, networked programs, and
system administration tools are all included. With every UNIX release, new tools
are being added and the older ones are modified/ removed

5. Pattern Matching :
Unix provides very sophisticated pattern matching features. The meta-char ‘*’ is
a special character used by the system to match several file names. There are
several other meta-char in UNIX. The matching is not confined to only filename.
Advanced tools use a regular expression that is framed with the characters from
this set.
6. Programming Facility:
Unix provides shell, which is also a programming language designed for
programmers, not for casual end-users. It has all the control structures, loops, and
variables required for programming purposes. These features are used to design
the shell scripts ( programs that can invoke the UNIX commands).
Many functions of the system can be controlled and managed by these shell
scripts.

7. Documentation:
It has a ‘man’ command that stands for the manual, which is the most important
reference for any commands and their configuration files. Apart from the online
documentation, there is a vast number of resources available on the Internet.

B What is the absolute and relative path? Explain with example.

Ans-Absolute path: An absolute path refers to the complete details needed to locate
a file or folder, starting from the root element, and ending with the other
subdirectories. Absolute paths are used in websites and operating systems for
locating files and folders.

An absolute path is also known as an absolute pathname or full path.

Example: To write an absolute path-name:


 Start at the root directory ( / ) and work down.
 Write a slash ( / ) after every directory name last one is optional
For Example:
cat /home/kt/abc.sq
Relative path: Relative Path is the hierarchical path that locates a file or folder on a
file system starting from the current directory. The relative path is different from
the absolute path, which locates the file or folder starting from the root of the file
system.

It is also called non-absolute pathway or partial pathway.

Example:  A relative path-name uses one of these cryptic symbols:


.(a single dot) - this represents the current directory.
..(two dots) - this represents the parent directory.

$pwd
/home/kt/abc
$cd ..
$pwd
/home/kt

C) What are the security levels available in UNIX?


Ans- Security levels are a facility which allows to scale global control over the
system to several levels. There are 8 security levels, from 0 (the least secure) to 7
(the most secure). For each level of access control, the 3 bits correspond to three
permission types. For regular files, these 3 bits control read access, write access,
and execute permission. For directories and other file types, the 3 bits have
slightly different interpretations.
Security Level 0 : Default mode, normal operation. Everything is allowed as in
the default unsecured Linux system.
Security Level 1 : Almost normal operation but the most dangerous actions. This
means direct write access to raw block devices.
Security Level 2 : This completely locks user space into itself, preventing to
modify or sidestep the kernel in any way.
Security Level 3 : Try to make sure that the configuration cannot be altered
unauthorizedly. Makes it impossible to change immutable and append file
attributes.
Security Level 4 : System prevents us to touch the network interfaces
configuration and routing table and iptables rules.
Security Level 5 : Attempt to protect running processes from any possible
unauthorized distractions.
Security Level 6 : By now all the special privileges of the root account are
disabled.
Security Level 7 : This is left for other special security modules as the
placeholder for any further possible restrictions.
D) What is filter? Is it possible to append contents using cat command? How
to display the 5th to 10th line of a file f1? How to open the last modified file in
VI editor?

Ans-Filters are programs that take plain text as standard input, transform it into a
meaningful format, and then return it as standard output. Some of the most used
filters are cat, head, tail, sort, uniq, grep etc.

Yes, it is possible to append contents using cat command. To append contents


double greater than sign (>>) is used in a file which has already exists. Example:
cat >> college.

To display the 5th to 10th line of a file f1 we run the following code :

cat f1 | head | tail -6

cat f1 | head | tail -5

cat f1 | tail +5 | head

cat f1 | tail -5 | head -10

To open the last modified file in vi editor we use :

vi `ls -tr | tail -1`

8. A) Name five administrative functions that cannot be performed by a


general user?

Ans-the five administrative functions that cannot be performed by a general user


are:

(i)General users can’t bootstrap in a UNIX system usually called in it .

(ii)General Users can’t login into other programs that ask users for credentials and
in case of successful authentication allows them to run programs with privilege of
their account.

(iii)General users are not authorized for configuring network interface.


(iv)They can’t create or modify a new user account.

(v)They can’t monitories the system for to ensure the correct operation.

B) What are the commands used by system administrator to create, modify,


and delete user accounts? Give example.

Ans- to create an account useradd command is used

Example: useradd -d homedir -g groupname -m -s shell -u userid accountname

To modify an account usermod command is used

Example: To change the account name mcmohd to mcmohd20 and to change home
directory accordingly, we will need to issue the following command :

$ usermod -d /home/mcmohd20 -m -l mcmohd mcmohd20

To delete an account userdel command is used

There is only one argument or option available for the command .r, for removing
the account's home directory and mail file.

Example to remove account mcmohd20, issue the following command –

$ userdel -r mcmohd20

C) What is the difference between su and su-aloke?

Ans- su is one of the core utilities in Linux. It allows users to execute commands as
another user. The most common use of the su is to get super user privileges. It is
often mistaken as an abbreviation for “super user”, but it is an abbreviation for
“substitute user”. The su command is used to switch to another user, in other words
change user ID during a normal login session.

While on the other hand


When we use su – , command changes our current working directory to the home
directory of the target user.

su-aloke: Here target user is aloke and by running this command the password is
required to access.

D) What are activities performed by shutdown command?

Ans- The shutdown command in Linux is used to shut down the system in a safe
way. It brings the system down in a secure way. When the shutdown is initiated, all
logged-in users and processes are notified that the system is going down, and no
further logins are allowed.

Only root user can execute shutdown command.

Syntax of shutdown Command

shutdown [OPTIONS] [TIME] [MESSAGE]

• options – Shutdown options such as halt, power-off (the default option) or reboot
the system.

• time – The time argument specifies when to perform the shutdown process.

• message – The message argument specifies a message which will be broadcast to


all users.

Options

-r : Requests that the system be rebooted after it has been brought down.

-h : Requests that the system be either halted or powered off after it has been
brought down, with the choice as to which left up to the system.

-H : Requests that the system be halted after it has been brought down.

-P : Requests that the system be powered off after it has been brought down.

-c : Cancels a running shutdown. TIME is not specified with this option, the first
argument is MESSAGE.
-k : Only send out the warning messages and disable logins, do not actually bring
the system down.

E) What are block and character devices?

Ans) There are two main types of devices under all UNIX systems, character and
block devices.

Block Devices tend to be storage devices, capable of buffering output and storing
data for later retrieval.

Character Devices are things like audio or graphics cards, or input devices like
keyboard and mouse.

Character devices are those for which no buffering is performed, and block
devices are those which are accessed through a cache. Block devices must be
random access, but character devices are not required to be, though some are. File
systems can only be mounted if they are on block devices.

F) What are the different run levels in UNIX?

Ans- Run levels determine which programs can execute after the operating system
boots up. The Run level defines the state of the machine after boot. Run levels are
numbered from zero to six.

run level 0 shuts down the system

run level 1 single-user mode

run level 2 multi-user mode without networking

run level 3 multi-user mode with networking

run level 4 user-definable

run level 5 multi-user mode with networking


run level 6 reboots the system to restart it

9. A) Differentiate between Multiprogramming and Multitasking.


Ans-
Multiprogramming Multitasking
It allows multiple programs to utilize the A supplementary of the
CPU simultaneously. multiprogramming system
also allows for user
interaction.
Based on the context switching mechanism. Based on the time-sharing
mechanism.
It is useful for reducing/decreasing CPU idle It is useful for running
time and increasing throughput as much as multiple processes at the
possible. same time, effectively
increasing CPU and system
throughput.
When one job or process completes its In a multiprocessing system,
execution or switches to an I/O task in a multiple processes can
multi-programmed system, the system operate simultaneously by
momentarily suspends that process. It allocating the CPU for a
selects another process from the process fixed amount of time.
scheduling pool (waiting queue) to run.
In a multiuser environment, the CPU In a single-user
switches between programs/processes environment, the CPU
quickly. switches between the
processes of various
programs.
It takes maximum time to execute the It takes minimum time to
process. execute the process.

B .What is the difference between the following vi commands?


(i): w (ii) : q! (iii) : wq (iv) zz.
Ans- (i) :w - Write out the file to save changes.
(ii) :q! - Quit vi but don’t save changes.
(iii) :wq - Save the file exit vi.
(iv) zz - Save the file exit vi

C)What do you mean by link of a file? What is symbolic link? Why is it


needed?
Ans- A link in UNIX is a pointer to a file. Like pointers in any programming
languages, links in UNIX are pointers pointing to a file or a directory. Creating
links is a kind of shortcuts to access a file. Links allow more than one file name to
refer to the same file, elsewhere.
There are two types of links:
1. Soft Link or Symbolic links
2. Hard Links

A symbolic link, also termed a soft link, is a special kind of file that points to
another file, much like a shortcut in Windows or a Macintosh alias. Unlike a hard
link, a symbolic link does not contain the data in the target file. It simply points to
another entry somewhere in the file system.
Symbolic links are needed because it uses all the time to link libraries and make
sure files are in consistent places without moving or copying the original. Links are
often used to “store” multiple copies of the same file in different places but still
reference to one file.

10. A) what is unique command? Explain with example.


Ans - The uniq command in Linux is a command line utility that reports or filters
out the repeated lines in a file. 
In simple words, uniq is the tool that helps to detect the adjacent duplicate lines
and deletes the duplicate lines. uniq filters out the adjacent matching lines from
the input file that is required as an argument and writes the filtered data to the
output file . 

Syntax of uniq Command: 


$uniq [OPTION] [INPUT[OUTPUT]]

EXAMPLE: $cat name.txt


My name is Megha.
My name is Megha.
My name is Megha.
I am from Jamshedpur.

$uniq name.txt
My name is Megha.
I am from Jamshedpur.

B)Arrange the data of a file in ascending and descending orders.


Ans- sort command is used to sort a file, arranging the records in a particular order.
By default, the sort command sorts file in ascending order.
Example: first creating a file
Command:
$ cat > file.txt
Abhishek
satish
rajan
naveen
harsh
For Ascending order:
Command:
$ sort file.txt
Output :
abhishek
harsh
naveen
rajan
satish
For Descending order: We can perform a reverse-order sort using the -r flag. the -r
flag is an option of the sort command which sorts the input file in reverse order i.e.
descending order by default.
Command:

$ Sort -r file.txt

Output:

Satish

rajan

naveen

harsh

abhishek

C) Write a shell script to check whether a file is readable, writable, or


executable.

Ans- SHELL SCRIPT

echo -n "Enter file name : "

read file

# find out if file has write permission or not

[ -w $file ] && W="Write = yes" || W="Write = No"

# find out if file has execute permission or not

[ -x $file ] && X="Execute = yes" || X="Execute = No"

# find out if file has read permission or not

[ -r $file ] && R="Read = yes" || R="Read = No"

echo "$file permissions"

echo "$W"
echo "$R"

echo "$X"

B. Explain the command to print all characters in a file.

Ans - The wc command in UNIX is a command line utility for printing newline,
word and byte counts for file. It can return the number of lines in a file, the number
if characters and the no. of words.

To print all characters in a file, command is : $ wc -c <filename>

11. Write short notes on any three of the following:


a) hard link and soft link

Hard link - Hard Link acts like a mirror copy of the original file. These
links share the same inodes. Changes made to the original or hard-linked file
will reflect in the other. When we delete Hard Link, nothing will happen to
the other file. Hard links can't cross file systems. Each hard linked file is
assigned the same Inode value as the original; therefore they reference the
same physical file location. Hard links more flexible and remain linked
even if the original or linked files are moved throughout the file system,
although hard links are unable to cross different file systems.
ls -l command shows all the links with the link column shows number of
links. Links have actual file contents. Removing any link, just reduces the
link count, but doesn’t affect other links. Even if we change the filename of
the original file then also the hard links properly work.
We cannot create a hard link for a directory to avoid recursive loops.
If original file is removed, then the link will still show the content of the
file. The size of any of the hard link file is same as the original file and if
we change the content in any of the hard links then size of all hard link
files are updated. The disadvantage of hard links is that it cannot be created
for files on different file systems, and it cannot be created for special files
or directories.
Command to create a hard link is: 
$ ln [original filename] [link name]

Soft link - A soft link is referred to as a shortcut in Windows or Mac


operating systems and a symbolic link or symlinks on UNIX-based systems.
A soft link is like the file shortcut feature which is used in Windows
Operating systems. Each soft linked file contains a separate Inode value
that points to the original file. As like hard links, any changes to the data in
either file are reflected in the other. Soft links can be linked across different
file systems, although if the original file is deleted or moved, the soft
linked file will not work correctly (called hanging link).
ls -l command shows all links with first column value l? and the link points
to original file.
Soft Link contains the path for original file and not the contents.
Removing soft link doesn’t affect anything but removing original file, the
link becomes “dangling” link which points to non-existent.
A soft link can link to a directory.
Size of a soft link is equal to the name of the file for which the soft link is
created. E.g., If name of file is file1 then size of its soft link will be 5 bytes
which is equal to size of name of original file.
If we change the name of the original file, then all the soft links for that file
become dangling i.e., they are worthless now.
Link across file systems: If you want to link files across the file systems,
you can only use symlinks/soft links.
Command to create a soft link

$ ln -s [original filename] [link name]

b) Internal and external commands


Ans- Internal Commands: Commands which are built into the shell. For all
the shell built-in commands, execution of the same is fast in the sense that
the shell doesn’t have to search the given path for them in the PATH
variable, and no process needs to be spawned for executing it.
Examples: source, cd, fg, etc.
External Commands: Commands which aren’t built into the shell. When
an external command must be executed, the shell looks for its path given in
the PATH variable, and also a new process has to be spawned and the
command gets executed. They are usually located in /bin or /usr/bin. For
example, when you execute the “cat” command, which usually is at /usr/bin,
the executable /usr/bin/cat gets executed.
Examples: ls, cat etc.

c) Mounting and Un-Mounting partitions


Ans-Mounting partition: The mount command mounts a storage
device or file system, making it accessible and attaching it to an
existing directory structure. All files accessible in UNIX, or a Unix-style
system such as Linux, are arranged in one big tree: the file hierarchy, rooted
at /. These files can be spread out over several devices. The mount command
attaches a file system, on some device or other, to the file tree. Conversely,
the umount command detaches it again.
The standard form of the mount command is:

mount -t type device dir

Unmounting partition: The umount command "unmounts" a mounted file


system, informing the system to complete any
pending read or write operations, and safely detaching it.
The umount command detaches the specified file system(s) from the file
hierarchy. A file system is specified by giving the directory where it was
mounted. Giving the special device on which, the file system lives may also
work, but is an obsolete method, mainly because it fails in case this device
was mounted on more than one directory.

d) Unmask and chmod.


Ans- Unmask: The unmask (UNIX shorthand for "user file-creation mode
mask") is a four-digit octal number that UNIX uses to determine the file
permission for newly created files. Every process has its own unmask,
inherited from its parent process.
The unmask specifies the permissions you do not want given by default to
newly created files and directories. unmask works by doing a bitwise AND
with the bitwise complement of the unmask. Bits that are set in the unmask
correspond to permissions that are not automatically assigned to newly
created files.
By default, most UNIX versions specify an octal mode of 666 (any user can
read or write the file) when they create new files. Likewise, new programs
are created with a mode of 777 (any user can read, write, or execute the
program). Inside the kernel, the mode specified in the open call is masked
with the value specified by the unmask - thus its name.

Chmod : In Unix and Unix-like operating systems, chmod is the command


and system call used to change the access permissions of file system objects
sometimes known as modes. It is also used to change special mode flags
such as setuid and setgid flags and a 'sticky' bit. The request is filtered by the
unmask. There are three basic file system permissions, or modes, to files and
directories: read (r) write (w).
For example, to add the execute permission for the user to file1:
chmod u+x file1
To remove the write permission for others for file2:
chmod o-w file2
We can combine multiple references and modes to set the desired access all
at once. For example, to explicitly make file3 readable and executable to
everyone:
chmod ugo=rx file3
The all (a) mode is the same as ugo, allowing the previous command to be
expressed as:
chmod a=rx file3

e) gzip and gunzip.

Ans- gzip is a file format and a software application used for file
compression and decompression. gzip command compresses files. Each
single file is compressed into a single file. The compressed file consists of a
GNU zip header and deflated data.
If given a file as an argument, gzip compresses the file, adds a “.gz” suffix,
and deletes the original file. With no arguments, gzip compresses the
standard input and writes the compressed file to standard output.
Syntax :
gzip [Options] [filenames]

Example:
$ gzip mydoc.txt

Gunzip is a command-line tool for decompressing Gzip files.


Gzip is one of the most popular compression algorithms that reduce the size
of a file and keep the original file mode, ownership, and timestamp
gunzip command is used to compress or expand a file or a list of files in
Linux. It accepts all the files having extension as .gz, .z, _z, -gz, -z , .Z, .taz
or.tgz and replace the compressed file with the original file by default. The
files after uncompressing retain its actual extension.
Syntax:
gunzip [Option] [archive name/file name].

You might also like