Transcript

1

Linux Basics and Shell Scripting

Presentation by V.SANTOSH

2

Agenda

• Linux, Unix Essentials• Vi editor• Unix, Linux Architecture• File, Process• Directory Structure• Basic commands• Permissions for files, dirs• Shell Scripting

Linux History

• 1984: The GNU Project and the Free Software Foundation• Creates open source version of UNIX utilities• Covered by General Public License (GPL) ( Copy Left)• Software license enforcing open source principles• 1991: Linus Trovalds• Creates open source, UNIX-like kernel, released under the GPL• Ports some GNU utilities, solicits assistance online• Today:• Linux kernel + GNU utilities = complete, open source, UNIX-like

operating system• Packaged for targeted audiences as distributions

4

Introduction to Linux

• Unix was one of the earliest OS • It was a proprietary OS• Richard Stallman and others started theFSF(Free Software Foundation)• GNU (GNU Not Unix) = A project of FSF provided the shell and applications for the new OSLinux Trovalds in 1991 provided the kernelAnd the new OS was called Linux.

5

Introduction to Linux Contd.

• Linux is an Open Source OS meaning the source code is free.• Open Source means freedom of Speech

6

Different Linux Distributions ( Distros)•

1) Fedora = Test bed for new applications etc.

For testing , Free no support

2) Redhat ,SUSE = Stable used in production environment Not free we need to subscribe, we Get support.

3) Debian = Free, no support Used for testing, used in production Environment to some extent

4) Mandrinova = Free, no support Used for testing, used in production Environment to some extent

5) Ubuntu = Free, no support Used for testing, used in production Environment to some extent Good for client machines

7

Features of Linux

• Open Source OS• Multiuser• Multitasking• Stable and robust OS• Less prone to virus attacks

8

Linux principles

• Everything is a file (including hardware)• Small, single-purpose programs• Ability to chain programs together to perform

complex tasks• Avoid captive user interfaces• Configuration data stored in text

9

Production Environment Features

• Recent Kernel Developments• Filesystems: Mundane and Advanced• Disk Striping and RAID• Parallel Processing and Clustering• Enterprise Networking Features

10

Unix, Linux Architecture

• Typical computer system consists of:– Hardware– Operating system– Applications and utilities

• Typical OS includes a user interface or command interpreter

• Unix is somewhat unique in that the command interpreter is not integrated with the OS but is a separate program

11

Layered Architecture of Linux and Unix

• Kernel= Performs core functions of the OS Interacts with Hardware• Shell= Interface between the user and the Kernel . Performs the command interpretation• Utilities, Applications

12

Directory Structure

• All the files are grouped together in the directory structure. The file-system is arranged in a hierarchical structure, like an inverted tree. The top of the hierarchy is traditionally called root (written as a slash / )

13

File and process• Everything in UNIX is either a file or a process. • A process is an executing program identified by a unique PID (process

identifier). • A file is a collection of data. They are created by users using text editors,

running compilers etc. • Examples of files: • a document (report, essay etc.) • the text of a program written in some high-level programming language • instructions comprehensible directly to the machine and

incomprehensible to a casual user, for example, a collection of binary digits (an executable or binary file);

• a directory, containing information about its contents, which may be a mixture of other directories (subdirectories) and ordinary files.

14

Linux Directory StructureDirectory Purpose/boot Contains kernel, bootloader and initrd /bin Essential command binaries/dev Device files/etc system configuration files.server config

files/home Home dir for regular users/lib Essential shared libraries and kernel

modules./proc Pseudo filesystem used by kernel for its

Processes/root Home dir for root user/sbin Essential command binaries generally

used by super user/tmp Folder for temporary files all users have

Full permission here with sticky bit set/usr The base directory for most shareable,

read-only data (programs, libraries,documentation, and much more).

/var mail and printer spools, log files, lock files, etc.

/media,/mnt Mount points for removable media

15

Logging into a Linux System

• Two types of login screens: virtual consoles (text-based) and graphical logins (called display managers)

• Login using login name and password • Each user has a home directory for personal

file storage

16

Virtual Consoles

• By default, we have :• 6 CUI virtual consoles ctrl + alt +f1 upto f6• 1 Graphical console

17

Changing Password

• Passwords control access to the system • To change your password using GNOME,

navigate to System->Preferences->About Me and then click Password.

• To change your password from a terminal: passwd

18

Basic Command Syntax

• command options arguments • Options are switches for additional info• Arguments are file or dirnames or anyOther data required by the commandEx : ls –l /root ls = command-l = long listing (option)/root =Argument

19

Command Help

Different levels of help • whatis <command> Single line info about the

command• command –help Short help with switches • man <command> complete help (manual pages) • info <command> Information regarding the command• /usr/share/doc/<command-version> folder has files

containing documentation regarding the command • Red Hat documentation =www.redhat.com/docs for guides,howtos etc

20

Basic commands

• Command What it does• pwd present working directory

ls content of pwdll similar as ls, but provides additional info on files and directories ll –a includes hidden files (.name) as well ll –R lists subdirectories recursively ll –t lists files in chronological orderstat <file_name> provides all attributes of a file whoami shows as who you are logged in

hostname shows on which machine you are

21

File , Directory Naming Rules

• Names may be up to 255 characters • All characters are valid, except the forward-

slash• It may be unwise to use certain special

characters in file or directory names • Some characters and space should be

protected with quotes when referencing them

• File, Dir Names are case-sensitive

22

Path = Absolute path ,relative path

Absolute pathnames• Begin with a forward slash• Complete "road map" to file location • Can be used anytime you wish to specify a file name Relative pathnames• Do not begin with a slash• Specify location relative to your current working

directory• Can be used as a shorter way to specify a file name

23

Creating dir , filesCommand Purpose

mkdir < dirname> To create a dir

touch < filename> Creates a zero byte file or empty file

cat > <filename> Creates a file with content save and exitWith ctrl +d

cat <filename> Displays the contents of the file

tac <filename> Displays the contents of the file inreverse

24

Changing directories

• Command Purpose• cd <path > change to that directory• cd .. change to a directory one level up• cd change to your home directory • cd - change to your previous working dir

25

How to list directory contents ?

• ls command Lists the contents of the current directory or a specified directory

• Syntax: ls [options] [files_or_dirs]

• ls -a (include hidden files)• ls -l (display extra information)• ls -R (recurse through directories)• ls -ld (directory and symlink information)

26

Copy files and dirs

• cp – command to copy files and directories • Syntax : cp [options] <source> <destination> • More than one file may be copied at a time if

the destination is a directory: Ex : cp [options] filea fileb dest Note : the last argument should be a dir

27

Renaming files and dirs

• mv – command to move and/or rename files and directories

• Syntax : mv [options] <source> <destination>• More than one file may be moved at a time if the

destination is a directory:• mv [options] file1 file2 destination• Note : Last argument must be a dir in case of moving mutiple filesIf the destination does not exist, the file will beRenamed.

28

Deleting files

• rm – command to remove files• Syntax : rm [options] <file>...Example:• rm -i file (interactive)= Prompts the user

before deletion• rm -r directory (recursive)• rm -f file (force)=Does not prompt the user, deletes the file forcefully

29

Deleting directories

• rmdir <dirname> removes empty directories• rm -r <dirname> recursively removes directory trees Note : use rm –r with caution always check with ls –R <dirname> before deletionOr combine with i i.e. rm –ri <dirname> =Prompts before deleting each file and the dir

30

Check file type

• Files can contain many types of data • We need to check file type with file before

opening to determine appropriate command or application to use

• file [options] <filename>

31

Seven fundamental file types

• - regular file• d directory• l symbolic link or soft link• b block special file Ex: hdd /dev/hda or /dev/sda• c character special file Ex: serial port /dev/ttyS0,

parallel port /dev/lp0 • p named pipe used to pass data bw processes• s socket End point for communication

32

Important commands for system info

Sl No Command Description

1.2.3.4.5.6.7.

8.9.

10.

11,

pswiddfdu “du -s” top

freecat /proc/cpuinfocat /proc/meminfouname –a

Lists currently running process (programs).Show who is logged on and what they are doing.Print your user-id and group id'sReport filesystem disk space usage (“Disk Free” is how I remember it)Disk Usage in a particular directory. provides a summaryfor the current directory.Displays CPU processes in a full-screen GUI. A great way to see theactivity on your computer in real-time. Type “Q” to quit.Displays amount of free and used memory in the system.Displays information about your CPU.

Display lots of information about current memory usage.

Prints system information to the screen (kernel version, machine type,etc.)

33

Vi Editor

• Vi is a powerful editor • Vi stands for visual editor

34

Agenda

• We need to know the vi editor before we learn shell scripting.

• Use vi editor to: – create text files– edit text files

• Our Goal is to create and run a shell scripts

35

Creating a file with vi

• Type vi <filename> at the shell prompt• After pressing enter the command prompt

disappears and you see tilde(~) characters on all the lines

• Tilde characters indicate that the line is blank

36

3 modes in vi

1. Command mode (Default mode)2. Insert mode = to Insert Text3. Ex mode = To save to save and quit quit without saving etc.

37

Command mode in vi

• Command mode is the default mode in vi• The moment you open the file with vi <filename> , you are in command mode• In command mode is for :i. Cursor movementii. Copyiii. Paste (yank)iv. Cut or deletev. Go to etc.

38

Cursor movement in vi

• Cursor movement is possible only in command mode in vi• Arrow keys may work• Standard keys for cursor movement are:i. h - for left ii. l - for rightiii. j - for downiv. k - for up

39

Cursor movement (continued)

• w - to move one word forward• b - to move one word backward• $ - takes you to the end of line• <enter> takes the cursor the the beginning of

next line• - (Minus) – takes the cursor to the beginning of the current line

40

Cursor movement continued

• ) - moves cursor to the next sentence • } - move the cursor to the beginning of next

paragraph• ( - moves the cursor backward to the

beginning of the current sentence • { - moves the cursor backward to the

beginning of the current paragraph• % - moves the cursor to the matching

parentheses

41

Manipulating text in Command Mode

Change (replace) Delete (cut) Yank(copy)• Letter cl dl yl • Word cw dw yw• Line cc dd yy• Sentence c) d) y) after • Sentence c( d( y( before • Paragraph c{ d{ y{ • above • Paragraph c} d} y}• below

42

Put in cursor mode

• p - Paste the yanked lines from buffer to the line below

• P - Paste the yanked lines from buffer to the line above

(the paste commands will also work after the dd or ndd command (cut a line and paste or

cut no. of lines and paste respectively)

43

Navigating in the screen (Commandmode)

• H - takes the cursor to the beginning of the current screen (Home)

• L - moves to the last line of the screen• M - moves to the middle line on the current

screen

44

File Positioning (Command Mode)

• G = takes cursor to last line of file (Go to last line)

• 1G= takes cursor to first line of file (Go first line)

• XG=takes cursor to that line of the file (where X is the line no.)

45

Insert Mode

• Insert Mode = to insert the text• Press <insert> key to enter insert mode after which you can type the text.a = append after cursorA = Append after linei = insert before cursorI = Insert before lineo = opens a new lineO = opens new line above

46

Undo and redo

• . u undo most recent change • U undo all changes to the current line• Ctrl-r redo last "undone" change

47

Search in Command Mode

• Search as in less or in man pages• / <string> to search,• n next search in that order• N previous search in that order

48

Search/Replace in vi editor

• Search/Replace as in sed • Affects current line by default • Use m,n ranges (where m is first line and n is the

last line in the range)• or % for whole file• :1,10s/find string/replace with string/g• :%s/find string/replace with string/gi • s = search, g=more than one instance per line , i = case insensitive

49

Ex mode

• :q <enter> to exit, if no changes are made to the file

• :q! <enter> to quit forcibly abandoning changes

• :wq <enter> to save and Exit• :x <enter> same as above• ZZ to save and Exit (uppercase)

50

Configuring vi

Few configuration options :• :set number• :set autoindent• :set showmatch• :set ignorecase

51

Making configurations in vi permanent

• To make the configurations permanent, you have to add this in ~/.vimrc and ~/.exrcas follows : # vi ~/.vimrc : se nu

52

Types of variables• Shell Variables or Local variables Shell variables or local variables exist only in the current shell instance.#c=6echo $c = Displays 6#vi xecho $csh x = Displays a blank as variable cannot be accessed within the file since it is a local variable and not exported• Environmental variables or global variables. These variables can be passed on to the subshells by exporting the variables.Add the command # export c in the command line, it becomes an

environmental variableThen sh x will display 6

53

System Variables

• System Variable Purpose• BASH=/bin/bash shell name• BASH_VERSION=1.14.7(1) shell version

name• COLUMNS=80 No. of columns for our screen• HOME=/home/student Our home directory• LINES=25 No. of rows for our screen• LOGNAME=student login name• OSTYPE=Linux Our Os type

54

System Variables continued

• PATH=/usr/bin:/sbin:/bin:/usr/sbin Our path settings

• PS1=[\u@\h \W]\$ Our prompt settings• PWD=/home/student Current

working directory• SHELL=/bin/bash Our shell name• USERNAME=student User name who is

currently login to this system

55

Examples of System Defined Variables

• PS1, PS2• PS1=System Prompt 1 ex: PS1= [\u@\h \W]\$ is the default bash

prompt• PS2=System Prompt 2 • Default value of PS2= “ >”

56

Types of varaiables

• User defined variables = variables defined by the user. Is case sensitive, can be defined in any case. Ex: #c=6 # echo $c 6• System defined variables =Defined by the

system used to configure the shell environment System defined variables are in upper case

57

Examples of System Defined Variables

• PS1, PS2• PS1=System Prompt 1 ex: PS1= [\u@\h \W]\$ is the default bash

prompt• PS2=System Prompt 2 • Default value of PS2= “ >”

58

Assigning the output of a command to a variable

– Using backquotes, we can assign the output of a command to a variable:

filelisting=`ls -l` echo $filelisting

59

Examples of System defined variables(Continued)

• PATH = Path variable points to the path or directory to search for the executables or command ex: /bin,/sbinLOGNAME=Login name of the userHOME=Home Directory of the user=Default Working directory of the userMAIL=Path where the mail of the user is stored Default path in RHEL for mail

/var/spool/mail/<username>

60

Examples of System defined variables(Continued)

• SHELL=Defines the default working shell• TERM=Defines the name of the current working terminal

61

Rules for defining UDV and systemvariable

• h

• UDV and System Variable)

• (1) Variable name must begin with Alphanumeric character or underscore character (_), followed by one

• or more Alphanumeric character. For e.g. Valid shell variable are as follows

• HOME• SYSTEM_VERSION

62

Rules for defining UDV and systemvariable (continued)

• (2) Don't put spaces on either side of the equal sign when assigning value to variable. For e.g. In

• following variable declaration there will be no error

• # num=15

63

Rules for defining UDV and systemvariable (continued)

• (3) Variables are case-sensitive, just like filename in Linux. For e.g.

• #num=15• # NUM=25• # NUm=15• # nUM=21• Above all are different variable name,

so to print value 25 we have to use $ echo $NUM

64

Rules for defining UDV and systemvariable (continued)

• (4) You can define NULL variable as follows (NULL variable is variable which has no value at the time

• of definition) For e.g.• # new=• # new=""• Try to print it's value by issuing following command• $ echo $new• Nothing will be shown because variable has no value i.e.

NULL variable.• (5) Do not use ?,* etc, to name your variable names.

65

Exit Status

• used to check whether command or shell script executed is successful or not.

• (1) If return value is zero (0), command is successful.

• (2) If return value is nonzero, command is not successful or some sort of error executing command/shell script.

• This value is know as Exit Status.echo $? Displays the exit status.• .

66

Redirectors

• < used to redirect input from file• > used to redirect output to file• 2> used to redirect error• & to redirect error and output• 2>&1 to redirect error and output=usedwith pipes

67

Examples for redirection

• tr ‘a-z’ ‘A-Z’ < <filename>= redirects inputFrom file instead of from keyboard.tr= translates lower case to upper case and vice versa• find /etc –name hosts > x will find all filesWith the name hosts under /etcand redirects to

the file x (Syntax for find: find <path> <criteria>)

68

Pipes

• Pipes (the | character) can connect commands: • command1 | command2 Sends STDOUT of

command1 to STDIN of command2 instead of the screen.

• STDERR is not forwarded across pipes • Multiple pipes : Used to combine the

functionality of multiple tools • command1 | command2 | command3... etc

69

Examples of redirection (contd).

• find /etc –name hosts 2> y =redirects all errors while executing the command to the fileY• find /etc –name &> z = will redirect both opand error to the file z.• find /etc –name 2>&1 | more=gives bothoutput and error from find command to theCommand more

70

Filters

• In Unix and Unix-like operating systems, a filter is a program that gets most of its data from its standard input (the main input stream) and writes its main results to its standard output (the main output stream). Unix filters are often used as elements of pipelines. The pipe operator ("|") on a command line signifies that the main output of the command to the left is passed as main input to the command on the right.

71

Unix, Linux Filter commands .cat = displays file content .cut = used to cut a field or character from a file or output of

command.expand = expands spaces to tab spaces in a file . pr =format before printing• grep = searches for a string / pattern and displays the entire line• head = display first ten lines of file by default• sed = stream line editor= search and replace strings or patterns• sh • sort = sorts a file or command output in ascending or descending• order• tail =displays the last ten lines of a file

72

Linux, Unix filters continued

• tac =concatenate and print files in reverse• tee = used with mulitiple pipes writes to file and pipes• tr = translates upper case to lower case and vice versa• uniq =report or omit repeated lines• wc = word count, no.of lines, no. of words, byte count from file or output

of command

73

Examples of filters in Linux, Unix

• cat hello.txt | wc | mail -s "The count" [email protected]

• head hello.txt• tail hello.txt• wc hello.txt• uniq hello.txt• sort hello.txt

74

Filters

Filter What it doescat Concatenates and

displays filespg Paginates display

For terminalsmore Displays a file

screenful at a timehead Prints the first ten

lines of a file by default

75

Filters (Contd.)

• tail Tail displays the last Ten lines of a file by default• grep Searches for a pattern and displays• The line which contains the pattern• sort Sorts files

76

Advanced Linux

• User administration• File System• Advanced File systems

77

User administration

• useradd [ options] <username> create user• usermod [options] <username> modify user• userdel <username> deletes a user, does not delete home diruserdel –r <username> deletes user and his home dir

78

Managing groups

• groupadd [Options} <groupname> creates group

• Groupmod [options] <groupname> modifiesGroupGroupdel <groupname> to delete a group

79

PermissionsThree types of permissions on files and dirs :• Permission : what action can be performed on the file• Permissions:

1. Read (r) = to read contents of a file or list contents of dir

2. Write (w) =to delete or modify the file, for dir to create or del files in the dir

3. Execute (x ) = to execute the file as a program, for dir to cd to that dir

Permissions are given for User<owner>, group that ownsThe file or dir and others (everyone else)

80

Changing permissions for fileor dir

• Symbolic Method :• chmod u=rw,g=r,o=x < filename> Assign

permissions• chmod u+rw,g+w,o+x <file or dir> Append Permissions• chmod u-w,o-r,g-r <file or dir> Delete or remove permissionsAbove permissions with chmod –R <dirname>= to Recursively change permissions of dir

81

Numeric Permissions

• r-4, w-2, x-1• Ex: chmod 755 <dir or file>Gives rwx for user(owner),rw for group and othersViewing permissions:ls –l <file or dirname> see the first column-rwxrw-rw- = 1 bit type of file, 2,3,4 user(owner), 5,6,7 for group,8,9,10 for others

82

Filesystems

1. File System is a method for storing and organizing computer files and the data they contain, to make it easy to find and access the files.

2. It may use a data storage device such as hard disk or CD-ROM and involve maintaining the physical location of the files.

3. Mostly File System make use of an underlying data storage device that offers access to anarray of fixed-size blocks called Sectors, generally of 512 bytes each.

4. They typically have directories which associates filename with files.

5. Examples are FAT (File Allocation Table), NTFS, ext2,ext3, ext4 etc.

83

Linux Filesystem in Depth

• Partitions and Filesystems• Disk drives are divided into partitions • Partitions are formatted with filesystems, allowing users

to store data • Default filesystem: ext3, the Third Extended Linux

Filesystem • Other common filesystems: • ext2 and msdos (typically used for floppies) • iso9660 (typically used for CDs) • GFS and GFS2 (typically for SANs)

84

Inodes

• An inode table contains a list of all files in an ext2 or ext3 file system

• An inode (index node) is an entry in the table, containing information about a file (the metadata), including:

• file type, permissions, UID, GID • the link count (count of path names pointing to this file) • the file's size and various time stamps • pointers to the file's data blocks on disk other data about the file

85

Directories

• The computer's reference for a file is the inode number

• The human way to reference a file is by file name

• A directory is a mapping between the human name for the file and the computer's inode number

86

cp and inodes

• The cp command:• Allocates a free inode number, placing a new

entry in the inode table • Creates a dentry in the directory, associating a

name with the inode number • Copies data into the new file

87

mv and inodes

• If the destination of the mv command is on the same file system as the source, the mv command:

• Creates a new directory entry with the new file name • Deletes the old directory entry with the old file name • Has no impact on the inode table (except for a time

stamp) or the location of data on the disk: no data is moved!

• If the destination is a different filesystem, mv acts as a copy and remove

88

rm and inodes

• The rm command: • Decrements the link count, thus freeing the

inode number to be reused • Places data blocks on the free list • Removes the directory entry • Data is not actually removed, but will be

overwritten when the data blocks are used by another file

89

Hard Links

• A hard link adds an additional pathname to reference a single file

• One physical file on the filesystem • Each directory references the same inode number • Increments the link count • The rm command decrements the link count • File exists as long as at least one link remains • When the link count is zero, the file is removed • Cannot span drives or partitions • Syntax: • ln filename [linkname]

90

Symbolic (or Soft) Links

• A symbolic link points to another file • ls -l displays the link name and the referenced file • lrwxrwxrwx 1 joe joe 11 Sep 25 18:02 pf -> /etc/

passwd• File type: l for symbolic link • The content of a symbolic link is the name of the

file that it references • Syntax:• ln -s filename linkname

91

Checking disk free space

• df - Reports disk space usage • Reports total kilobytes, kilobytes used, kilobytes free per file

system • -h and -H display sizes in easier to read units • du - Reports disk space usage • Reports kilobytes used per directory • Includes subtotals for each subdirectory • -s option only reports single directory summary • Also takes -h and -H options • Applications->System Tools->Disk Usage Analyzer or baobab -

Reports disk space usage graphically

92

Removable Media

• Mounting means making a foreign filesystem look like part of the main tree.

• Before accessing, media must be mounted • Before removing, media must be unmounted • By default, non-root users may only mount certain

devices (cd, dvd, floppy, usb, etc) • Mountpoints are usually under /media • RH033-RH033-RHEL5-en-2-20070306 Copyright ©

2007 Red Hat, Inc.• All rights reserved

93

Mounting CDs and DVDs

• Automatically mounted in Gnome/KDE• Otherwise, must be manually mounted• CD/DVD Reader• mount /media/cdrom • CD/DVD Writer• mount /media/cdrecorder • eject command unmounts and ejects the disk

94

Mounting USB Media

• Detected by the kernel as SCSI devices • /dev/sdaX or /dev/sdbX or similar• Automatically mounted in Gnome/KDE • Icon created in Computer window • Mounted under /media/Device ID • Device ID is built into device by vendor

95

Archiving Files and Compressing Archives

• Archiving places many files into one target file • Easier to back up, store, and transfer • tar - standard Linux archiving command • Archives are commonly compressed • Algorithm applied that compresses file • Uncompressing restores the original file • tar natively supports compression using gzip

and gunzip, or bzip2 and bunzip2

96

Creating, Listing, and Extracting File Archives

• Action arguments (one is required):• -c create an archive • -t list an archive • -x extract files from an archive • Typically required:• -f archivename name of file archive • Optional arguments:• -z use gzip compression • -j use bzip2 compression • -v be verbose

97

Advanced Filesystems

• LVM= Logical Management for online resizing of partitions• RAID = Redundant Array of Inexpensive Disks for redundancy , performance

98

SHELL SCRIPTING

• Shell scripts are like batch files • Shell scripts are used to :• automate the tasks.• for repetitive tasks• Customising the work environment• Executing various administrative tasks

99

Creating a shell script

• # vi samplescript.sh #!/bin/bash = Magic sh bang sequence which indicates interpreter to use(not compulsory if You are running a bash script in a bash shell) echo “hello world”

100

Executing a shell script

• sh samplescript = to execute the script or• chmod 700 samplescript (gives full

permissions rwx for owner of the file) ./samplescript = to execute the script

101

Shell keywords

• echo = for output prints whatever is mentioned after that word on the screen

( can be redirected)Ex: echo “hello” = displays hello• read = for input Ex: read name takes input from keyboard and stores the value in the variable name.(other keywords will be discussed throughout This presentation)

102

Shell Keywords

echo shift esacread export break if then continue fi for exitelse while returnset until unset do readonly umask case eval

103

Handling Output

• echo = Used to display on the screen• Ex: echo “hello world”

104

Handling Input

• read <Variable> = to take input from keyboard and store the value in the variableEx: The following script takes the name as input from keyboard and displays the name and welcome statement # vi inout.shecho –n “enter your name: “read name echo “$name,welcome to the Shell Scripting class”

105

Arithmetic Calculations in Shell Script

• expr = Expression=For evaluating an arithmetic expression.

• Ex: #vi calc a=2 b=3echo “sum=`expr $a + $b`echo “sum=$sum”

106

Arithmetic Operators in Shell Scripting

The following operators can be used with expr in Shell Scripting for calculations 1. Addition +2. Substract –3. Multiplication \*4. Division / (Quotient)5. Modular Division % (Remainder)

107

Assignment 2

• Write a program to input 2 nos.,Calculate and print the following :1. Sum2. Difference3. Product4. Quotient5. Remainder

108

Positional Parameters

• Positional parameters is a convenient way to pass data to a program.• can be considered as variables defined by the

shell.• These are named $1 to $9• While $0 indicates the program name.

109

Example of Positional Parameters

• You can write a program to add 2 nos. and pass values to the program.

#vi adder echo “usage: sh adder $1 $2 ex: sh adder 2 3”sum=`expr $1 + $2` echo $sum

110

Assignment 3

• Write a program to pass values to a program from command line and perform the following:Input studentname marks in 5 subjects ,Calculate and print the following:Studentname Phy Chem Maths Eng Hin (Marks)Total marks and average marks

111

Using Shift in Positional Parameters

• shift is a shell builtin that operates on the positional parameters. Each time you invoke shift, it "shifts" all the positional parameters down by one. $2 becomes $1, $3 becomes $2, $4 becomes $3, and so on.

• By default , moves the positional parameters to the right by one• We can shift by more than one • By giving the command shift nWhere n is the no. of times to shiftEx: shift 3 ,shifts position by 3

112

shell script example for Shift in positional parameters

#vi ppshift#!/bin/bash echo “Usage: sh ppshift par1 par2 par3 par4echo “We start with $# positional parameters“echo “First Parameter is $1" echo “Second Parameter is $2”echo “Third Parameter is $3”# Shift parameters by one (Default is 1 you can use shift n where#n is the no. of parameters you want to shift)shiftecho "You now have $# positional parameters“echo “First Parameter now is $1" echo “Second Parameter now is $2”echo “Third Parameter now is $3”

113

Important topics

• Login shells and non login shells in bash• Process Management

114

Login scripts in bash

• Scripts executed when we login• /etc/profile – Default profile for all users Environmental variables PATH Scripts under /etc/profile.d are run in a for loop/etc/profile.d/* - Dir contains application specific

scripts~/.bash_profile – User specific profile

115

Non login scripts in bash

• ~/.bashrc = User specific Bashrc• /etc/bashrc= Default bashrc for all users(global) Aliases Umasks=Provide default permission for files and dirs umask for root is 022 umask for regular user is 002 Functions

116

Test command

• Evaluates boolean statements for use in conditional execution

• Returns 0 for true• Returns 1 for false• Examples in long form:• $ test "$A" = "$B" && echo "Strings are equal"

$ test "$A" -eq "$B" && echo "Integers are equal" • Examples in shorthand notation:• $ [ "$A" = "$B" ] && echo "Strings are equal"

$ [ "$A" -eq "$B" ] && echo "Integers are equal"

117

Assignment

• Write a shell script to compare 3 nos. using test

• Write a shell script to compare 2 strings using test

118

Structures in Shell Scripting

• There are 3 types of structures in Shell• Scripting :1. Sequential Structure2. Conditional Structure3. Repetitive Structure

119

Sequential Structure

• In Sequential structure, commands are executed in sequence one after the other.Ex: All the shell scripts we discussed so far are sequential structures.

120

Conditional Structures

• In conditional structures, • Commands are executed based on a condition.

Similar to conditional control structures in programming languages, there are some differences.

1. The if condition tests the success of a Linux command, not an expression.

2. The end of an if-then command must be indicated with the keyword fi, and

3. the end of a case command is indicated with the keyword esac.

121

Syntax for if ..then

• Syntax:• If [Condition]; then statement elif [Condition]; thenstatementelsestatement fi Note: 1) If ,then is used in next statement, ;(semicolon) is not required2) elif is similar to else if in other programming languages

122

Assignment 4

1) Write a shell script to input 2 nos. and print whether they are equal or not. If notEqual, print the greatest of the 2 nos.Using if..then2) Write a shell script to input 2 stringsand display whether they are equal or notUsing if ..then

123

case in shell scripts

• Case is generally used to select from a no. of alternatives

• We can print a menu and ask the user to choose from a no. of alternatives.

124

Syntax of case

Syntax : Case choice in 1) command ;; 2) command;; 3) Command;;

*) echo “invalid entry”;;EsacNote: 1) * indicates a value other those

mentioned in the menu. 2) every option is terminated with ;;

125

Repetitive Structures

• In repetitive structures, commands are executed repetitively in a loopEx: 1) for Loop2) while Loop3) until Loop

126

Syntax of “ for loop”• Syntax: for variable in list of values do statement doneEx: for i in 1 2 3 4 5 do echo $i doneOutput : 1 2 3 4 5

127

More Examples of for loop

# print nos. from 1 to 10 using for for i in {1..10}do echo $idoneOutput: Prints nos. from 1 to 10 using forNote: # is used for comment in any shell script statements or commands in a line beginning with # will not be executed.

128

For loop with increment other than 1

• Example: for i in $(seq 1 3 10) do | | | echo $i (first no, increment, last no.) done Output: 1 3 7 10 will be displayed one below the other.

129

For Loop with a decrement of 1

• Example: for i in $(seq 10 -2 2) do | | | echo $i (first no, increment, last no.) done Output: 10 8 7 6 4 2 will be displayed one

below the other.

130

Assignment 5

1) Write a shell script to print the nos. from 1 to 10 and their squares using for.2) Write a shell script to print the even and odd nos. from 1 to 10 using for

131

Nested for loops

• Nested for loops are loops within a loop• Generally used for printing patterns etc.• The first pass of the outer loop starts the inner

loop, which executes to completion. Then the second pass of the outer loop starts the inner loop again. This repeats until the outer loop finishes.

132

Examples of Nested for loops• # vi nestedfor for i in {1..5} do for j in (seq 1 1 $i)v do echo –n $j doneechoDoneOutput: prints the following pattern112123123412345

133

Assignment 6

• 1. Write a program to print the followingPatterns :i) 12345 ii) * 1234 * * 123 * * * 12 * * * * 1 * * * * *

134

While Loop

• The commands within a while loop are executed repetitively as long as the condition is true.Syntax : while [ condition]doCommand 1Command 2done

135

While loop example

• # Program to print the nos. from 1 to 10 using whilec=1 while [ $c –le 10 ]do echo $cc=`expr $c + 1`done

136

Examples of Decrement in WhileLoop

#Program to print the nos. from 1 to 10In reverse order using whilec=10while [ $c -gt 0 ]doecho $cc=`expr $c - 1`done

137

Continue, Break and Exit

• While loop can be interrupted during execution :

• Continue : Reexamines the loop and restarts the loop• Break : Exits the loop• Exit : Exits the program itself

138

Until Loop

• The commands within an until loop are executed repetitively as long as the condition is false.Syntax :until [ condition]doCommand 1Command 2done

139

Until loop Example

• # Program to print the nos. from 1 to 10 using untilc=1 until [ $c –gt 10 ]do echo $cc=`expr $c + 1`done

140

Assignment 7

• Write a program to print the even and odd nos. between 1 and 10 using while and until

141

Assignment 8

• Write a shell script to print the nos. from 1 to 10 in reverse order using

until.• Write a shell script to input a no. and check whether it is prime or not.

142

Functions in Shell Scripting

• Functions are used in Shell Scripting to:1. Improve program readability2. Remove repetitive code from the scripts.

Note: Shell functions must be declared first

143

Functions syntax

• Declaring the Function : • Function Name (){Command 1Command 2}Calling the Function : Function Name

144

Example of Functions in Shell Scripting

• hellofn(){read -p “Enter Your Name: “ nameecho “$name, Welcome to the Shell Scripting Class”}hellofn

145

Passing Arguments to functions

• Passing argument to the functions in shell script is easy.

Use $1, $2, .. $n variables that represent arguments in the function just like the positional parameters we discussed earlier.

Note: $* indicates all arguments together

$# indicates the total no. of arguments

146

Examples of Passing arguments tothe function

adderfn(){ a=$1 b=$2 sum=`expr $a + $b` echo “sum=$sum”} adderfn $1 $2

147

Assignment 9

• Write a shell script using functions and passing arguments to functions to :

1. Copy a file 2. Move a file or rename filea to fileb Note :first create a small textfile and create theabove functions.

148

References

• http://www.versageek.com/ksh_munix.html• http://www.computer-realm.net/types-of-

operating-systems/• http://techforum4u.com/content.php/339-

File-System-In-Operating-System


Top Related