Docsity

Unix and Shell Programming 17CS35, Study notes of Computer Science

Partial preview of the text

Download Unix and Shell Programming 17CS35 and more Study notes Computer Science in PDF only on Docsity!

[As per Choice Based Credit System (CBCS) scheme]

(Effective from the academic year 2015 - 2016)

SEMESTER – III

Subject Code 15CS35 IA Marks 20

Number of Lecture Hours/Week 04 Exam Marks 80

Total Number of Lecture Hours 50 Exam Hours 03

CREDITS – 04

Module - 1 10 Hours Introduction, Brief history. Unix Components/Architecture. Features of Unix. The UNIX Environment and UNIX Structure, Posix and Single Unix specification. The login prompt. General features of Unix commands/ command structure. Command arguments and options. Understanding of some basic commands such as echo, printf, ls, who, date, passwd, cal, Combining commands. Meaning of Internal and external commands. The type command: knowing the type of a command and locating it. The man command knowing more about Unix commands and using Unix online manual pages. The man with keyword option and whatis. The more command and using it with other commands. Knowing the user terminal, displaying its characteristics and setting characteristics. Managing the nonuniform behaviour of terminals and keyboards. The root login. Becoming the super user: su command. The /etc/passwd and /etc/shadow files. Commands to add, modify and delete users. Module - 2 10 Hours Unix files. Naming files. Basic file types/categories. Organization of files. Hidden files. Standard directories. Parent child relationship. The home directory and the HOME variable. Reaching required files- the PATH variable, manipulating the PATH, Relative and absolute pathnames. Directory commands – pwd, cd, mkdir, rmdir commands. The dot (.) and double dots (..) notations to represent present and parent directories and their usage in relative path names. File related commands – cat, mv, rm, cp, wc and od commands. File attributes and permissions and knowing them. The ls command with options. Changing file permissions: the relative and absolute permissions changing methods. Recursively changing file permissions. Directory permissions. Module - 3 10 Hours The vi editor. Basics. The .exrc file. Different ways of invoking and quitting vi. Different modes of vi. Input mode commands. Command mode commands. The ex mode commands. Illustrative examples Navigation commands. Repeat command. Pattern searching. The search and replace command. The set, map and abbr commands. Simple examples using these commands. The shells interpretive cycle. Wild cards and file name generation. Removing the special meanings of wild cards. Three standard files and redirection. Connecting commands: Pipe. Splitting the output: tee. Command substitution. Basic and Extended regular expressions. The grep, egrep. Typical examples involving different regular expressions. Module - 4 10 Hours Shell programming. Ordinary and environment variables. The .profile. Read and readonly commands. Command line arguments. exit and exit status of a command. Logical operators for conditional execution. The test command and its shortcut. The if, while, for and case control statements. The set and shift commands and handling positional parameters. The here ( << ) document and trap command. Simple shell program examples. File inodes and the inode structure. File links – hard and soft links. Filters. Head and tail commands. Cut and paste commands. The sort command and its usage

with different options. The umask^ VTUNOTESBYSRI and default file permissions. Two special files /dev/null and /dev/tty.

MODULE 1: UNIX ARCHITECTURE AND COMMAND USAGE GENERAL PURPOSE UTILITIES ESSENTIAL SYSTEM ADMINISTRATION 1.1 Introduction

  1. 2 Unix Architecture 1.3 Features of Unix
  2. 4 POSIX and Single Unix Specification 1.5 The Login Prompt 1.6 Command Structure 1.6.1 Options 1.6.2 Filename Arguments 1.6.3 Exceptions 1.7 Understanding of Some Basic Commands 1.7.1 echo 1.7.2 printf 1.7.3 ls 1.7.4 who 1.7.5 date 1.7.6 passwd 1.7.7 cal 1.8 Flexibility of Command Usage 1.9 Internal and External Commands 1.10 type 1.11 man 1.11.1 man: Browsing the Manual Pages Online 1.11.2 Understanding the man Documentation 1.11.3 Using man to Understand man 1.11.4 Further Help with man – k, apropos and whatis 1.12 more 1.13 Knowing the User Terminal, Displaying its Characteristics and Setting Characteristics 1.13.1 uname : Knowing your Machines Characteristics 1.13.2 tty: Knowing your Terminal 1.13.3 stty: Displaying and Setting Terminal Characteristics 1.14 Managing the Nonuniform Behaviour of Terminals and Keyboards 1.15 Types of Accounts 1.15.1 The root Login 1.15.2 su: Becoming Super user 1.16 /etc/passwd and /etc/shadow Files 1.17 Managing Users and Groups 1.17.1 groupadd 1.17.2 Commands to Add, Modify and Delete users 1.17.2.1 useradd 1.17.2.2 usermod 1.17.2.3 userdel

VTUNOTESBYSRI

MODULE 1: UNIX ARCHITECTURE AND COMMAND USAGE 1.1 Introduction

  • UNIX is an operating system.
  • An operating system is a set of programs that act as a link between the computer and the user.
  • The operating system (OS) manages the resources of a computer.
  • Examples of computer resources are: CPU, RAM, disk memory, printers, displays, keyboard, etc. Figure 1.1 : Operating System
  • UNIX OS allows complex tasks to be performed with a few keystrokes.
  • UNIX OS doesn’t tell or warn the user about the consequences of the command.
  • Unix was originally developed in 1969 by a group of AT&T employees Ken Thompson, Dennis Ritchie, Douglas McIlroy, and Joe Ossanna at Bell Labs.
  • There are various Unix variants available in the market.
  • Solaris Unix, AIX, HP Unix and BSD are a few examples.
  • Linux is also a flavor of Unix which is freely available.

VTUNOTESBYSRI

**1. 3 Features of Unix

  1. Multiuser**
  • UNIX is a multiprogramming system.
  • Multiple users can access the system by connecting to points known as terminals.
  • Several users can run multiple programs simultaneously on one system. 2) Multitasking
  • UNIX is a multitasking system.
  • A single user can also run multiple tasks concurrently.
  • For example: At the same time, a user can → edit a file → print another file one on the printer → send email to a friend and → browse www
  • 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) Pattern Matching
  • UNIX has very sophisticated pattern matching features.
  • Regular Expressions are a feature of UNIX.
  • Regular Expressions describe a pattern to match, a sequence of characters, not words, within a line of text. 4) Portable
  • UNIX can be installed on many hardware platforms.
  • Unix operating system is written in C language, hence it is more portable than other operating systems. 5) UNIX Toolkit
  • UNIX offers facility to add and remove many applications as and when required.
  • Tools include → general purpose tools → text manipulation tools → compilers/interpreters → networked applications and → system administration tools 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.
  • This 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 shell scripts. 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.

VTUNOTESBYSRI

1. 4 POSIX and Single Unix Specification

  • The Portable Operating System Interface (POSIX) is a family of standards specified by IEEE for maintaining compatibility between operating systems.
  • Two of the most important standards from POSIX are:
    1. POSIX.1 – Specifies the C application program interface – the system calls (Kernel)
    2. POSIX.2 – Deals with the Shell and utilities
  • In 2001, a joint initiative of X/Open and IEEE resulted in the unification of two standards.
  • This is the Single UNIX Specification, Version 3 (SUSV3).
  • The “Write once, adopt everywhere” approach to this development means that once software has been developed on any POSIX machine it can be easily ported to another POSIX compliant machine with minimum or no modification. 1. 5 The Login Prompt How to log in
  • Have your userid (user identification) and password ready.
  • Type your userid at the login prompt, then press ENTER. Your userid is case sensitive, so be sure you type it exactly as your system administrator has instructed.
  • Type your password at the password prompt, then press ENTER. Your password is also case sensitive.
  • If you provide the correct userid and password, then you will be allowed to enter into the system.
  • While the prompt($) is displayed, you can type a command (say date). login: kumar kumar's password: ***** Last login: Sun Jun 14 09:32:32 2017 from 162.61.164. $ date Thu Jun 25 08:30:19 MST 20 17

VTUNOTESBYSRI

**1. 7 Understanding of Some Basic Commands

  1. 7 .1 echo**
  • This command can be used to display a message on the terminal.
  • Example: $ echo "Welcome to UNIX \n" Welcome to UNIX
  • This command can be used with following escape characters: "\a" Audible Alert (Bell) "\b‟ Back Space "\f‟ Form Feed "\n‟ New Line "\r‟ Carriage Return "\t‟ Horizontal Tab "\v‟ Vertical Tab "\‟ Backslash 1. 7 .2 printf
  • This command can be used to display a message on the terminal.
  • This command can be used with following escape characters: "\a" Audible Alert (Bell) "\b‟ Back Space "\f‟ Form Feed "\n‟ New Line "\r‟ Carriage Return "\t‟ Horizontal Tab "\v‟ Vertical Tab "\‟ Backslash
  • Example: $ printf "Welcome to UNIX \n" Welcome to UNIX
  • Similar to C language, this command can be used with following format specifiers: %d Decimal integer %f Floating point number %s String %o Octal integer (base 8) %x Hexadecimal integer (base 16)
  • Syntax: printf("format-string", variable-list); where format-string contains one or more format-specifiers variable-list contains names of variables
  • Example: $ printf "My current shell is %s\n" $SHELL My current shell is /bin/ksh 1. 7 .3 ls
  • ls command can be used to obtain a list of all filenames in the current directory.
    • l option can be used to obtain a detailed list of attributes of all files in the current directory.
  • Example: $ ls - l Type & Perm Link Owner Group Size Date & Time File Name
    • rwxr-xr-- 1 kumar metal 195 may 10 13:45 chap drwxr-xr-x 2 kumar metal 512 may 09 12:55 helpdir

VTUNOTESBYSRI

1. 7 .4 who

  • This command can be used to display the details of all the users logged-in into the unix system at the same time.
  • Example: $ who kumar tty0 Oct 8 14: rama tty2 Oct 4 09:
  • – H option can be used to display the header information.
  • Example: $ who NAME LINE TIME COMMENT kumar tty0 Oct 8 14: rama tty2 Oct 4 09:
    • u option can be used to display detailed information of users.
  • Example: $ who - Hu NAME LINE TIME IDLE PID COMMENT kumar tty0 Oct 8 14:10 00:18 185 rama tty2 Oct 4 09:08 00:23 123 1. 7 .5 date
  • This command can be used to display the current date and time.
  • Example: $ date Mon Sep 4 16:40:02 IST 2017
  • This command can also be used with suitable format specifiers as arguments.
  • Following are some format specifiers: d – day of month (1 - 31) m - Month (01-12) y – last two digits of the year. H– hour (00-24) M – minute (00-59) S – second (00-59) D – date in the format mm/dd/yy T – time in the format hh:mm:ss
  • Syntax: $ date +%format_specifier
  • Example: $ date +"%d-%m-%y" 04 - 09 - 17 $ date +%m // displays month number 09 1. 7 .6 passwd
  • This command can be used to change user password.
  • All Unix systems require passwords to help ensure that your files and data remain secure from hackers.
  • Following are the steps to change your password – 1 ) To start, type password at the command prompt as shown below. 2 ) Enter your old password, the one you're currently using. 3 ) Type in your new password. 4 ) You must verify the password by typing it again. $ passwd Changing password for kumar (current) Unix password: ***** New Unix password: ***** Retype new Unix password: ***** passwd: all authentication tokens updated successfully $

VTUNOTESBYSRI

1. 8 Flexibility of Command Usage

  • UNIX provides flexibility in using the commands.
  • A command can often be entered in more than one way.
  • Shell allow the following type of command usage:
    1. Combining Commands.
    2. A command line can overflow or Be split into multiple lines.
    3. Entering a command before previous command has finished. 1) Combining Commands
  • UNIX allows you to specify more than one command in the single command line.
  • Example: $ wc sample.txt ; ls – l sample.txt //Two commands separated by ; (semicolon). 2 3 1 6 sample.txt
    • rw-rw-r-- 1 kumar group 16 Jan 30 09:35 sample.txt $ ls | wc //Two commands combined here using filter
  • You can even group several commands together so that their combined output is redirected to a file. (wc sample.txt ; ls – l sample.txt) > newfile
  • When a command line contains a semicolon, the shell understands that the command on each side of it needs to be processed separately. Here ; is known as a metacharacter. 2) A Command line can 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 // > is a secondary prompt > text message” // Command line ends here This is a three-line text message 3 ) Entering a Command before previous command has finished
  • You need not have to wait for the previous command to finish before you can enter the next command.
  • Subsequent commands can be entered at the keyboard without waiting for prompt.
  • The input remains stored in a buffer maintained by kernel for all keyboard input.
  • The next command is passed on to the shell for interpretation after the previous program has completed. 1. 9 Internal and External Commands
  • Some commands are implemented as part of the shell itself rather than separate executable files. Such commands that are built-in are called internal commands.
  • If the command (file) has an independence existence in the /bin directory, it is called external command.
  • 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 internal command only.
  • Internal commands will have top priority compare to external command of same name.

VTUNOTESBYSRI

1.1 0 type

  • The UNIX is command based system i.e.,- things happens because the user enters commands in.
  • Usually, UNIX commands are less than 5 characters long.
  • All UNIX commands are single words like – cat, ls, pwd, date, mkdir, rmdir, cd, grep etc.
  • The command names are all in lowercase.
  • Example: $ LS bash: LS: command not found
  • All UNIX commands are files containing programs, mainly written in C.
  • All UNIX commands(files) are stored in directories(folders).
  • If you want to know the location of executable program (or command), use type command.
  • Example: $ type ls ls is /bin/ls
  • When you execute ls command, the shell locates this file in the /bin directory and makes arrangements to execute it.

VTUNOTESBYSRI

1.1 1 .3 Using man to Understand man

  • You can use man command to view its own documentation.
  • Example: $ man man //Viewing man pages with man
  • You can also set the pager to use with man ($ PAGER=less ; export PAGER).
  • To understand which pager is being used by man, use $ echo $PAGER. 1.1 1. 4 Further Help with man – k, apropos and whatis
  • man – k: Searches a summary database and prints one-line description of the command.
  • Example: $ man – k awk //To know what awk does awk (1) - pattern scanning and text processing language m awk (1) - pattern scanning and text processing language n awk (1) - pattern scanning and text processing language
  • apropos can be used to list the commands and files associated with a keyword.
  • Example: $ apropos awk //Same as $ man - k awk awk (1) - pattern scanning and text processing language m awk (1) - pattern scanning and text processing language n awk (1) - pattern scanning and text processing language
  • Example: $ whatis awk // Lists one-line description of command and same as $man - f awk awk (1) - pattern scanning and text processing language

VTUNOTESBYSRI

1.1 2 more

  • more command can be used to display the content of a file on the screen, one page at a time.
  • After each page, it stops and waits for you to tell it what to do.
  • If the file contents is more, it will show the filename and percentage of the file that has been viewed: ----More--- (15%)
  • Syntax: more FILENAME Navigation
  • Following two commands can be used for navigation:
    1. Spacebar or f – moves forward one screen
    2. b – moves back one screen
  • Finally, to quit the pager, press q.
  • You'll be returned to the shell's prompt($). Repeat Factor
  • The repeat factor used as a command prefix to repeat the command as many times as the prefix.
  • For example: → 10 f moves forward 10 screen. Here, 10 is acting as a repeat factor. Searching for a pattern
  • A pattern can be searched in a file using following 2 commands. Command Function /Pattern searches forward for pattern in the file.
  • Syntax: /Pattern [Enter] Repeating the Last Pattern Search
  • The previous search command can be repeated using following 2 commands: Command Function n repeats the previous search command in the same direction
  • n repeats search in same direction of original search. Using more in pipeline
  • Example: ls | more
  • Here, pipe (|) is used where the output of one command is used as the input of the other command. Table: Internal commands of more and less more less action spacebar or f spacebar or f one page forward 10f - 20 pages forward b b one page backward 10b - 20 pages backward [Enter] [Enter] one line forward
  • k one line back
  • p or 1G beginning of file
  • G end of file /Pattern /Pattern searches forward for pattern n n repeat search forward
  • ?Pattern searches backward for pattern .(dot) - repeat last command v v start vi editor !cmd !cmd executes unix command q q quit h h help

VTUNOTESBYSRI

1.1 4 Managing the Non-uniform Behaviour of Terminals and Keyboards

  • Terminals and keyboards have no uniform behavioral pattern.
  • Terminal settings directly impact the keyboard operation.
  • The following table lists keyboard commands to try when things go wrong. Keystroke or Command Function [Ctrl-h] Erases text [Ctrl-c] or Delete Interrupts a command [Ctrl-d] Terminates login session or a program that expects its input from keyboard [Ctrl-s] Stops scrolling of screen output and locks keyboard [Ctrl-q] Resumes scrolling of screen output and unlocks keyboard [Ctrl-u] Kills command line without executing it [Ctrl-] Kills running program but creates a core file containing the memory image of the program [Ctrl-z] Suspends process and returns shell prompt; use fg to resume job [Ctrl-j] Alternative to [Enter] [Ctrl-m] Alternative to [Enter] stty sane Restores terminal to normal status

VTUNOTESBYSRI

MODULE 1(CONT.): ESSENTIAL SYSTEM ADMINISTRATION 1.1 5 Types of Accounts There are 2 types of accounts on a Unix system: 1) Root Account

  • The system administrator is known as superuser or root user.
  • The superuser has complete control of the system. 2) User Accounts
  • User accounts provide interactive access to the system for users and groups of users.
  • General users are typically assigned to these accounts and usually have limited access to critical system files and directories. 1.1 5 .1 The root Login
  • The system administrator is known as superuser or root user.
  • The superuser has complete control of the system.
  • The superuser can run any commands without any restriction.
  • The job of superuser includes: → maintaining user accounts → providing security and → managing disk space → performing backups
  • The root account doesn’t need to be separately created but comes with every system.
  • The root account's password is generally set at the time of installation of the system and has to be used on logging in: Login: root Password: ********* [Enter]

    -

  • The command prompt of root is hash (#).
  • Once you login, you are placed in root’s home directory "/".
  • /sbin and /usr/sbin contains administrative commands of the system. 1.1 5. 2 su: Becoming Super User
  • Any user can acquire superuser status with the su command if they know the root password.
  • For example, the user "kumar" becomes a superuser in this way: $ su Password: *****

    pwd

    /home/kumar
  • Though the current directory doesn’t change, the # prompt indicates that kumar now has powers of a superuser.
  • To be in root’s home directory on superuser login, use su – l Creating a User’s Environment
  • User’s often rush to the administrator with the complaint that a program has stopped running.
  • The administrator first tries running it in a simulated environment.
  • su command with a – (hyphen) can be used to recreate the user’s environment without the login- password. su – kumar
  • This sequence executes kumar’s .profile and temporarily creates kumar’s environment.
  • su runs in a separate sub-shell, so this mode is terminated by hitting [ctrl-d] or using exit.

VTUNOTESBYSRI