Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views30 pages

Unix Unit1

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 30

UNIT-I: Introduction 12 hours

Introduction, History, Architecture, General Purpose Utilities: cat, cal, date, calendar, who, printf, tty,
sty, uname, passwd, echo, tput, bc. Introduction to Shell Scripting, Shell Scripts, read, Command Line
Arguments, Exit Status of a Command, The Logical Operators, exit, if, and case conditions, expr,
sleep and wait, while, until, for, redirection, set and shift, trap.

1. Unix Components/Architecture

2. Features of Unix

3. The UNIX Environment and UNIX Structure, Posix and Single Unix specification

4. General features of Unix commands/ command structure. Command arguments and options

5. Basic Unix commands such as echo, printf, ls, who, date,passwd, cal, Combining commands

6. Meaning of Internal and external commands

7. The type command: knowing the type of a command and locating it

8. The root login. Becoming the super user: su command

 Unix Components/Architecture

1.1 The Operating System


 An operating system is the software that manages the computer's hardware and provides
a convenient and safe environment for running programs.
 It acts as an interface between user programs and the hardware resources that these programs access
like – processor, memory, hard disk, printer & so on.
 It is loaded into memory when a computer is booted and remains active as long as the machine is up.
1.2 The UNIX Operating System
 Like DOS and Windows, there's another operating system called UNIX.
 UNIX is a giant operating system with sheer power.
 Developed by Ken Thompson and Dennis Ritchie.
 It runs practically on every Hardware and provided inspiration to the Open Source movement.
 You interact with a UNIX system through a command interpreter called the shell.
Unix Components/Architecture

Page 1
 The UNIX architecture has three important agencies-
 Division of labor: Kernel and shell
 The file and process

 The system calls


Division of labor: Kernel and shell
The Kernel
 The kernel interacts with the machine's hardware
 The core of the operating system - a collection of routines mostly written in C.
 It is loaded into memory when the system is booted and communicates directly with the
hardware.
 User programs (the applications) that need to access the hardware use the services of the
kernel, which performs the job on the user's behalf.
 These programs access the kernel through a set of functions called system calls.

 Apart from providing support to user's program, kernel also does important housekeeping.
 It manages the system's memory, schedules processes, and decides their priorities and so on.
 The kernel has to do a lot of this work even if no user program is running.
 The kernel is also called as the operating system - a programs gateway to the computer's
resources.

The Shell
 Computers don't have any capability of translating commands into action.
 That requires a command interpreter, also called as the shell.
 Shell is acts interface between the user and the kernel.
 Most of the time, there's only one kernel running on the system, there could be
several shells running – one for each user logged in.
 The shell accepts commands from user, if require rebuilds a user command,
andfinally communicates with the kernel to see that the command is executed.
 Example:
$echoVTU Belagavi #Shell rebuilds echo command by removing multiple spaces
VTU Belagavi

Page 2
 The following figure shows the kernel-shell Relationship:

The file and process


 Two simple entities support the UNIX – the file and the process.
 “Files have places and processes have life”
The File
 A file is just an array of bytes and can contain virtually anything.
 A file forms a Hierarchical file system.
 Every file in UNIX is part of the one file structure provided by UNIX.
 UNIX considers directories and devices as members of the file system.

The Process
 The process is the name given to the file when it is executed as a program (Process is
program under execution).
 We can say process is the “time image” of an executable file.
 UNIX provides tools to control processes move them between foreground and background and
killthem.

The System Calls


 The UNIX system-comprising the kernel, shell and applications-is written in C.
 Though there are several commands that use functions called system calls to communicate with the
kernel.
 All UNIX flavors have one thing in common – they use the same systemcalls. Eg: write, open

Page 3
 Features of Unix

1. A Multiuser System
 UNIX is a multiprogramming system, it permits multiple programs to run and compete for the
attention of the CPU.
 This can happen in two ways:
- Multiple users can run separate jobs
- A single user can also run multiplejobs
 A single user system where the CPU, memory and hard disks are all dedicated to a single user.
 In UNIX, the resources are shared between all users; UNIX is also a multiuser system.

2. A Multitasking System
 A single user can also run multiple tasks concurrently.
 UNIX is a multitasking system.
 It is usual for a user to edit a file, print another one on the printer, send email to a friend and browse
www- all without leaving any of applications.
 The kernel is designed to handle a user's multiple needs.
 In a multitasking environment, a user sees one job running in the foreground; the rest run in the
background.
 User can switch jobs between background and foreground, suspend, or even terminate them.

3. The Building-block Approach


 The designer never attempted to pack too many features into a few tools.
 Instead, they felt “small is beautiful”, and developed a few hundred commands each of which
performed one simple job.
 UNIX offers the | (filters) to combine various simple tools to carry out complex jobs.
 By interconnecting a number of tools , we can have a large number of combinations of their usage.
 Example:
$ cat note #cat displays the file contents
WELCOME TO BRCE
$ cat note | wc #wc counts number of lines, words & characters in the file
1 3 15
4. The UNIX Toolkit
 There are general-purpose tools, text manipulation utilities (filters), compilers and
interpreters , networked applications, system administration tools and shells.

5. Pattern Matching
 UNIX features very sophisticated pattern matching features.
 Example: The * (zero or more occurrences of characters) is a special character used by system

Page 4
toindicate that it can match a number of filenames.

6. Programming Facility
 The UNIX shell is also a programming language; it was designed for programmer, not for end user.
 It has all the necessary ingredients, like control structures, loops and variables, that establish
powerful programming language.
 These features are used to design shell scripts – programs that can also invoke UNIX commands.
 Many of the system's functions can be controlled and automated by using these shellscripts.
7. Documentation
 The principal on-line help facility available is the man command, which remains the most
important references for commands and their configuration files.
 Apart from the man documentation, there's a vast ocean of UNIX resources available on the Internet.

 UNIX Environment and UNIX Structure

 A variable that specifies how an operating system or another program runs, or the devices
that the operating system recognizes.

 Set of dynamic values that can affect the way running processes will behave on a computer.

 A string consisting of environment information, such as a drive, path, or filename,


associated with a symbolic name that can be used by MS-DOS and Windows.

 General features of Unix Commands/Command structure

Page 5
The following table lists keyboard commands to try when things go wrong.

 Basic Unix commands such as echo, printf, ls, who, date,passwd, cal, Combining
commands

1. echo: Displaying The Message

 echo command is used is shell scripts to display a message on the terminal, or to issue a
prompt for taking user input.

Page 6
$ echo "Enter your
name:\c" Enter your
name:$_

$echo $SHELL
/usr/bin/bash
 Echo can be used with different escape sequences

Constant Meaning
„a‟ Audible Alert (Bell)
„b‟ Back Space
„f‟ Form Feed
„n‟ New Line
„r‟ Carriage Return
„t‟ Horizontal Tab
„v‟ Vertical Tab
„\‟ Backslash
„\0n‟ ASCII character represented by the octal value n

2. printf: An Alternative To Echo

 The printf command is available on most modern UNIX systems, and is the one we can use
instead of echo. The command in the simplest form can be used in the same way as echo:

$ printf “Enter your


name\n” Enter your name
$_

 printf also accepts all escape sequences used by echo, but unlike echo, it doesn‟t
automatically insert newline unless the \n is used explicitly. printf also uses formatted
strings in the same way the C language function of the same name uses them:

$ printf "My current shell is %s\n" $SHELL


My current shell is /bin/bash
$_

 The %s format string acts as a placeholder for the value of $SHELL, and printf replaces %s
with the value of $SHELL. %s is the standard format used for printing strings. printf uses
many of the formats used by C‟s printf function. Here are some of the commonly used ones:

%s – String
Page 7
%30s – As above but printed in a space 30 characters wide
%d – Decimal integer
%6d - As above but printed in a space 30 characters wide
%o – Octal integer
%x – Hexadecimal integer
%f – Floating point number

Example:
$ printf "The value of 255 is %o in octal and %x in hexadecimal\n" 255 255

The value of 255 is 377 in octal and ff in hexadecimal

3. ls:listing directories and files

 The command to list your directories and files is ls.


 With options it can provide information about the size, type of file, permissions, dates of file
creation, change and access.
Syntax
ls [options] [argument]
 When no argument is used, the listing will be of the current directory. There are many very useful
options for the ls command. A listing of many of them follows. When using the command, stringthe
desired options together preceded by "-".
- a Lists all files, including those beginning with a dot (.).
- d Lists only names of directories, not the files in the directory
- F Indicates type of entry with a trailing symbol: executables with *, directories with / and
symbolic links
- R Recursive list
- u Sorts filenames by last access time
- t Sorts filenames by last modification time
- i Displays inode number
- l Long listing: lists the mode, link information, owner, size, last modification (time). If the file is
a symbolic link, an arrow (-->) precedes the pathname of the linked-to file.
- x multicolumnar output

$ls –ld helpdir progs


- drwxr-xr-x 2 kumar metal 512 may 9 10:31 helpdir
- drwxr-xr-x 2 kumar metal 512 may 9 09:57
progs output in multiple columns(-x):
$ ls –x
Page 8
Identifying Directories and executables(-F)
$ ls –Fx
Showing hidden files(-a)
$ ls -axF
Listing directory contents
$ ls -x

4. who: Who Are The Users


 UNIX maintains an account of list of all users logged on to the system. The who command
displays an informative listing of these users:

$ who
root tty7 2017-09-04 16:38 (:0)
root tty17 2017-09-04 16:38 (:0)
$_

 Following command displays the header information with –H option,


$ who -H
NAME LINE TIME
COMMENT root tty7 2017-09-
04 16:38 (:0)
$_

 -u option is used with who command displays detailed information of users:


$ who -Hu
NAME LINE TIME IDLE PID
COMMENT root tty7 2017-09-04 16:38 00:18
1865 (:0)
$_

5. date: Displaying The System Date

 One can display the current date with the date command, which shows the date and time to
the nearest second:
$ date
Mon Sep 4 16:40:02 IST 2017

 The command can also be used with suitable format specifiers as arguments. Each symbol is
preceded by the + symbol, followed by the % operator, and a single character describing the
format. For instance, you can print only the month using the format +%m:
Page 9
$date +%m
09
Or
the month name name:

$ date +%h
Aug
Or
You can combine them in one command:
$ date + “%h %m”
Aug 08

 There are many other format specifiers, and the useful ones are listed below:
- d – The day of month (1 - 31)
- y – The last two digits of the year.
- H, M and S – The hour, minute and second, respectively.
- D – The date in the format mm/dd/yy
- T – The time in the format hh:mm:ss
6. Passwd: Changing your password

 Password prevents from accessing the system


 If account doesn’t have password or has one that is already known to others, should change it
immediately.
 This can be done with passwd command:
$ passwd
passwd: changing password for Kumar
Enter login password: ******* Asks for old password
New password: ********
Re-enter new password: ********
passwd (SYSTEM): passwd successfully changed for Kumar
 Passwd expects you to respond three times. First, it primpts for the old password. Next, it schecks
whether you have entered a valid password, and if you have, it then prompts for the new password.
 Enter the new password using the password naming rules.
 Finally, passwd asks you to reenter the new password. Later, the new password is registered by the
system.
 Rules for framing your own password:
- Don’t choose a password similar to the old one.
- Don’t use commonly used names like names of friends, relatives, pets and so forth.
- Use a mix of alphabetic or numeric characters.
- Don’t write a password in an easily accessible document.
- Change the password regularly.
Page 10
7. cal: The Calendar

 cal command can be used to see the calendar of any specific month or a complete year.

Syntax:
cal [ [ month] year ]

 Everything within the rectangular box in optional. So cal can be used without any arguments, in
which case it displays the calendar of the current month

$ cal
September 2017
Su Mo Tu We Th Fr Sa
12
345 6 789
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

 The syntax show that cal can be used with arguments, the month is optional but year is not.
To see the calendar of month August 2017, we need to use two arguments as shownbelow,

$ cal 8 2017
August 2017
Su Mo Tu We Th Fr Sa
1 2 345
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

 You can‟t hold the calendar of a year in a single screen page; it scrolls off rapidly before you
can use [ctrl-s] to make it pause. To make cal pause using pager using the | symbol to connect
them.
$cal 2017 | more

8. Combining commands
 UNIX allows you to specify more than one command in the single command line.
Example:
$ wc note; ls -l note #Two commands combined here using ; (semicolon)
2 3 16 note
-rw-rw-r-- 1 mahesh mahesh 16 Jan 30 09:35 note

Page 11
In the above example, wc command returns number of lines, words and characters in that file, and
ls –l command returns list all the attributes of the file
 A command line can overflow or be split into multiple lines
 UNIX terminal width is restricted to maximum 80 characters.
 Shell allows command line to overflow or be split into multiple lines.
Example:
$ echo “This is # $ first prompt
> a three-line # > Second prompt
> text message” #Command line ends here

This is
a three-line text
message

 INTERNAL AND EXTERNAL COMMANDS

 When the shell execute command(file) from its own set of built-in commands that are not
stored as separate files in /bin directory, it is called internal command.
 They can be executed any time and are independent.
 If the command (file) has an independence existence in the /bin directory, it is called
external command.
 External commands are loaded when the user requests for them. It will have an individual
process.
Examples:
$ type echo # echo is an internal command
echo is shell built-in
$ type ls # ls is an external command
ls is /bin/ls

 If the command exists both as an internal and external one, shell execute internalcommand
only.
 Internal commands will have top priority compare to external command of samename.

 The type command: knowing the type of a command and locating it

 The type command is used to describe how its argument would be translated if used as commands. It
is also used to find out whether it is built-in or external binary file.

Page 12
 The type command is shell builtin.
Syntax:
type [Options] command names
 If you want to know the location of executable program (or command), use type
command-
Example:
$ type date
date is /bin/date
$ type echo
echo is a shell builtin

 When you execute date command, the shell locates this file in the /bin directory
and makesarrangements to execute it.
SHELL PROGRAMMING

1. Ordinary and environment variables.


2. The .profile.
3. Read and readonly commands
4. Command line arguments
5. . exit and exit status of a command.
6. Logical operators for conditional execution.
7. The test command and its shortcut.
8. The if, while, for and case control statements.
9. The set and shift commands and handling positional parameters.
10. The here (<<) document and trap command.
11. Simple shell program examples.

1. Ordinary and environment variables.


A local variable is a variable that is present within the current instance of the shell. It is not
available to program that are started by the shell. They are set at command prompt.

VARIABLE NAMES:
 A variable is a character string to which we assign a value. The value assigned could be a
number, text, filename, device, or any other type of data.
 A variable is nothing more than a pointer to the actual data. The shell enables you to create,
assign, and delete variables.
 The name of a variable can contain only letters(a to z or A to Z),numbers(0 to 9) or the
underscore character( _ ).
 By convention, Unix shell variables would have their names in UPPERCASE
 The following examples are valid variable names:-
VAR_1
VAR_2
TOKEN_A

DEFINING VARIABLE:
 Variable are defiened as follows:
 Variable_name= variable_value
 For example
NAME=”Sumithabha Das”
ACCESSING VARIABLES:
 To access the value stored in a variable, prefix its name with the dollar sign($).
 For example following script would access the value of defined variable NAME and would
print it on STDOUT
#!/bin/sh
NAME=”Sumitabha Das”
Echo $NAME

ENVIRONMENT VARIABLES:
An environment variables that is available to any child process of the shell. Some programs need
environment variables in order to function correctly. Usually a shell script defines only those
environment variables that are needed by the programs that it runs
 SHELL: points to the shell defined as default.
 DISPLAY: contains the identifier for the display that X11 programs should use by default.
 HOME: Indicates the home directory of the current user default argument for the cd built in
command
 IFS: Indicates the Internal Field Separator that is used by the parser for word splitting after
expansion.
 PATH: Indicates search path for commands .It is a colon separated list of directories in
which shell looks the command.
 PWD: Indicates the current working directory as set by the cd command.
 RANDOM: Generates a random interger between 0 and 32767 each time it s referenced.
 SHLVL: Increments by one each time an instance of bash is created.
 UID: Expands to the numeric user ID of the current user initialized at shell prompt.
Following is the sample example showing few environment variables
$ echo $HOME
/root
]$ echo $DISPLAY

$ echo $TERM
xterm
$ ech $PATH
/usr/local/bin:/bin:/usr/bin:/home/amrood/bin:/usr/local/bin
$

PS1(Prompt String one) and Environment variables


The characters that the shell displays as your command prompt are stored in the variables PS1.You
can change this variable to be anything you want .As soon as you change it it’ll be used by the shell
from that point on.
For example, if you issued the command:
$PS1=’=>’
=>
=>
Your prompt would become=>
When you issue a command that is incomplete, the shell will display a secondary prompt and wait
for you to complete the command and hit Enter again.
The default secondary prompt is > (the greater than sign), but can be changed by re-defining the
PS2 shell variable:
Following is the example which uses the default secondary prompt:
$ echo “this is a
>test”
This is a
test
$
$ PS=’-->’
$ echo “this is a
-->test”

2. The .profile File


 The file /etc/profile is maintained by the system administrator of your UNIX machine and contains
shell initialization information required by all users on a system.
 The file .profile is under your control .you can add as much shell customization information as you
want to this file. The minimum set fo information that you need to configure includes.
 The type of terminal you are using
o A list of directories in which to locate commands
o A list of variables effecting look and feel of you terminal.
 You can check your .profile available in your home directory. Open it using vieditor and check all
the variable set for your environment
Shell scripts
 When a group of commands have to be executed regularly thry should be stored in a file and the file
itself executed as a shell script or shell program.
Structure of shell script
#! /bin/sh
# script.sh: Sample shell script
echo “Todays date: ‘date’ ”
echo “This month’s calendar:”
cal ‘date’ “+%m 20%y”
echo “My shell: $SHELL”
Module 2_UNIX Programming (18CS56) 2021-2022
Module 2_UNIX Programming (18CS56) 2021-2022
Module 2_UNIX Programming (18CS56) 2021-2022

Prof. Mamatha B Dept of CSE Page 28


Module 2_UNIX Programming (18CS56) 2021-2022

Prof. Mamatha B Dept of CSE Page 29


Module 2_UNIX Programming (18CS56) 2021-2022

Prof. Mamatha B Dept of CSE Page 30

You might also like