Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
180 views

Unix Basic Material

eS The document provides an overview of Linux basics including: 1) The Linux kernel manages system resources and allows users to interact through a shell. 2) The file system is hierarchical with directories branching into other directories and files in a tree structure. 3) All data is organized into files within directories in a tree-like structure called the file system. re

Uploaded by

Manoj Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
180 views

Unix Basic Material

eS The document provides an overview of Linux basics including: 1) The Linux kernel manages system resources and allows users to interact through a shell. 2) The file system is hierarchical with directories branching into other directories and files in a tree structure. 3) All data is organized into files within directories in a tree-like structure called the file system. re

Uploaded by

Manoj Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 73

040-23752633 LINUX BASICS MATERIAL

INDEX
SL.NO. CONTENTS PAGE NO.
01 INTRODUCTION 2-2
02 UNIX ARCHITECTURE 3-4
03 THE UNIX FILESYSTEM 5-6

ies
04 BASIC COMMANDS 6 - 17
05 LINK FILES 17 - 18
06 WHAT IS A PATH 18 - 20

og
07 FILE PERMISSIONS 20 - 25
08 Vi EDITOR 25 - 28

ol
09 FIND FILES 29 - 33
10 AWK 34 - 37

hn
11 SED (STREAM EDITOR) 37 - 39
12 COMMUNICATION COMMANDS 39 - 43
13 PROCESS MANAGEMENT c 43 - 52
Te
14 SHELL SCRIPTING 53 - 53
15 SHELL SUPPORT FEATURES 54 - 57
ai

16 TYPE OF OPERATORS 57 - 61
17 CONTROL STATEMENTS 61 - 71
eS

18 POSITIONAL PARAMETERS 72 - 72
19 FILE TEST 72 - 73
re

20 MISCELLANEOUS 73 - 73
Sh

LINUX BASICS MATERIAL 1 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

INTRODUCTION
What is UNIX?

The UNIX operating system is a set of programs that act as a link between the computer and the user.

The computer programs that allocate the system resources and coordinate all the details of the computer's
internals is called the operating system or kernel.

ies
Users communicate with the kernel through a program known as the shell. The shell is a command line
interpreter; it translates commands entered by the user and converts them into a language that is

og
understood by the kernel.

Unix was originally developed in 1969 by a group of AT&T employees at Bell Labs, including Ken

ol
Thompson, Dennis Ritchie, Douglas McIlroy, and Joe Ossanna.

hn
There are various Unix variants available in the market. Solaris Unix, AIX, HP Unix and BSD are few
examples. Linux is also a flavor of Unix which is freely available.

c
Several people can use a UNIX computer at the same time; hence UNIX is called a multiuser system.
Te
A user can also run multiple programs at the same time; hence UNIX is called multitasking.
ai

HISTORY OF UNIX:-0020
eS

Before development of Unix operating system at AT & T Bell Labs, Software team lead by ken
Thomson Dennis Ritchie and Rudd Candy worked on MULTICS project . MULTICS stands for Multi
Information Computing System. The aim of this project is to share the same data by ‘n’ number of
re

users at the same time. Initially, MULTICS was developed for only two users .Based on the same
concept in 1969,UNICS operating system was developed for 100’s of users.UNICS stands for uniplexed
Sh

information Computing System. Initially UNICS was written Assembly Language in 1973 they written in
‘c’ Language named as UNIX

LINUX BASICS MATERIAL 2 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

UNIX ARCHITECTURE

Usr

Shell

Kernal

ies
HW

og
ol
c hn
Te
KERNEL
ai

Kernel is used in UNIX like systems and is considered to be the heart of the operating system. It is

responsible for communication between hardware and software components. It is primarily used for
eS

managing the systems resources as well.

Kernel Activities:
re

 The Kernel task manager allows tasks to run concurrently.


Sh

 Managing the computer resources: Kernel allows the other programs to run and use the resources.
Resources include i/o devices, CPU, memory.
 Kernel is responsible for Process management. It allows multiple processes to run simultaneously

allowing user to multitask.


 Kernel has an access to the systems memory and allows the processes to access the memory when
required.
 Processes may also need to access the devices attached to the system. Kernel assists the processes
in doing so.
 For the processes to access and make use of these services, system calls are used.

LINUX BASICS MATERIAL 3 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

SHELL

Linux shell is the user interface to communicate with Linux operating system. Shell is a command checker
.It’s origin of “c” Language. Shell interprets the user requests, executes them. Shell may use kernel to
execute certain programs. Shell Script: A shell script is a program file in which certain Linux commands are
placed to execute one after another. A shell script is a flat text file. Shell scripts are useful to accept inputs

ies
and provide output to the user. Everyday automation process can be simplified by a shell script.

THE HIERARCHICAL FILE SYSTEM.

og
The Unix file system called as hierarchical file system. In fact, within the Unix system, There is no limit to

the number of files and directories you can create in a directory that you own. File systems of this type are

ol
often called tree-structured file systems, because each directory allow you to branch off into other

directories and files . The Unix file system resembles an upside down tree.

c hn
Te
ai
eS
re
Sh

LINUX BASICS MATERIAL 4 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

THE UNIX FILESYSTEM.

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 filesystem.

When you work with UNIX, one way or another you spend most of your time working with files. This
tutorial would teach you how to create and remove files, copy and rename them, create links to them

ies
etc.

In UNIX there are three basic types of files:

og
Ordinary Files: An ordinary file is a file on the system that contains data, text, or program instructions.
In this tutorial, you look at working with ordinary files.

ol
Directories: Directories store both special and ordinary files. For users familiar with Windows or Mac

hn
OS, UNIX directories are equivalent to folders.

Special Files: Some special files provide access to hardware such as hard drives, CD-ROM drives,
c
modems, and Ethernet adapters. Other special files are similar to aliases or shortcuts and enable you to
Te
access a single file using different names.
ai

/root: This is root directory of the file system, the main directory of the entire file system, and the
eS

root directory for the super user.

/bin: bin stands for binary. This directory contains executable files for most of the Unix
re

commands. This command used by normal user also.


Sh

/sbin: This directory contains all system admin executable files (or) commands. This contains
programs used in booting the system and in system recovery.

/etc :- This directory contains all system configuration files and the files which maintain
information about users and groups. Ex. Group Name, G.I.D, User Name, U.I.D.

/usr:- This is user name directory. Default directory provided by unix O.S. to create users home
directories and contains manual pages.

/tmp:- This directory contains all temporary files used by the Unix system. System on users
creates temporary files which will be removed when the server reboots.

LINUX BASICS MATERIAL 5 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

/dev:- This directory contains all logical device files it maintains device for information’s directory.
Ex. All disks devices are in the subdirectory /dev/dsk.

/devices:- This directory contains physical devices files.

/home: - Default directory allocated for the home directory of normal users when the administrator
don’t specify any other directory. If your log name is root (or) sai, your default home directory is

ies
/home/root (or) sai.

/Var:- It directory all system log files and message files.

og
/lib:- This directory contains all the library functions. Provided by UNIX programmers.

ol
/kernel This directory contains platform independent loadable kernel modules required as part of the
boot process.

hn
/mnt:- It contains entries for removable (mountable) media such as cd-roms and DLT Tapes.

c
Te
Basic Commands:-
# Pwd : It display the present (current) working directory ex: PWD ┘
ai

# Logname : It display the initial user name ex: logname ┘


eS

# Clear : It clear the screen

# exit : To logout from current account.


re

# Date : It displays the current system date & time. Mon Mar 12 010:10:10 IST 2009
Sh

# who : It display the list of users who are currently logged in to the server.

ie. Each user logname, terminal No, date & time that the person logged in

# finger : It displays complete information about all the users who are logged in to the users who

are logged in to the server with more details.

# whoami : It displays current username, terminal no, data $ time at which you logged in the

system.

# Cal : It displays the previous month, current month and next month calendar.

LINUX BASICS MATERIAL 6 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

# Cal year : It display the given year calendar cal 2009 it takes year from 1 to 9999

# su : It used to switch from one user to another user.

# Cal month year : It display the given month, year cal only

# Where is <command> : It display the location of the given command.

ies
Ex: where is pwd ┘

# Banner : It prints a message in large letters

og
ex: banner sai ┘

# init : To change the system run levels.

ol
# init Ө : To shut down the system (ok boot prompt)

hn
# init 1 : To bring the system to single user mode.

Without network, without GID (single user mode)

c
Te
# init 2 : To bring the system to multi user mode with

no resource shared. (Multi user mode) no files having


ai

# init 3 : To bring the system multi user mode but CLI mode with source shared. (with sharing)

multi user
eS

# init 4 : To future use


re

# init 5 : To bring the system into complete GUI mode.


Sh

# init 6 : To restart the (or) (reboot) the system.

# where is [option] command :

Options: -b → report binary files only

-m → report manual sections only

-s → report source files only

Creating Files: There are two commands to create files

Touch and Cat

LINUX BASICS MATERIAL 7 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

Touch : It creates zero byte file size touch does allow you to store anything in a file. It is used for

to create several empty files quickly.

Ex : touch 1 2 3 4 5 

Cat : It is used for create a new file (or) to open a exiting file (or) to append the data to the file

ies
Ex : # cat > file name 

- - - - - -- - - - -- > redirect input

og
------------------ >“ “ output

Control + d {to close a file}

ol
To open the file :

hn
Ex : # cat > file name

(or) c
Te
Cat filename
ai

To append the data to the file


eS

Ex : # cat >> file name

-------
re

-------
Sh

Control + d

To Open the multiple file

Ex : # cat 1 2 3 4 

# cat 1 2 > 3

# cat [ options] [file]

Options :

-n → Precede each line with a line number.


LINUX BASICS MATERIAL 8 www.shreesaitechnologies.com
040-23752633 LINUX BASICS MATERIAL

-v → Display non-printing characters, except tabs, new – lines and form – feeds

-e → display $ at the end of each line (prior to new – line) (when used with –v option)

Removing Files :

# rm : To remove the given file & folders.

ies
Sy:- # rm file name 

Options :

og
-i : it asks confirmation before deleting the file

ol
Sy : # rm –i file name 

hn
Remove file name? y – It removes

N – It won’t remove

c
Te
To remove the multiple files:

Syntax: # rm file1 file2 file3 ……… it removes three files


ai

# rm * → it removes all files in current directory.


eS

Creating Directory:
re

# mkdir : [option] directory : it is used for to create a new directory

ex : mkdir /sai
Sh

Options :-

-p → create the parent directories as needed.

-m(mode) → `access permissions

Creating multiple directories

# mkdir sai sai1 sai2 

# mkdir -p /a1/a2/a3

Change Directory :
LINUX BASICS MATERIAL 9 www.shreesaitechnologies.com
040-23752633 LINUX BASICS MATERIAL

Sy:- # cd /directory name 

# cd /sai 

# pwd 

- /sai

ies
# cd…. to change in to parent directory

# cd  to change to root directory.

og
Remove Directory: - A Directory need to be empty before you can remove it. If it’s not, you need to
remove the files first also. You can’t remove a directory if it is your present working directory. You must first

ol
change out of it.

hn
Syntax : - # rm dir /dir name  to delete a directory but directory should be empty.

Options:-
c
Te
-r → it removes all files and sub directories, sub directory files including directory.
ai

-i → it asks the conformation before deleting the directory.


eS

Rename a file :- Rename a file with the move command “m”

# v (options) old file name new file name.


re

Options :-
Sh

-i → Interactive (prompt an wait for confirmation before proceeding)

-f → don’t prompt, even when copying over an existing target file (overrides – i)

Cp (copy) :- To copy data one file to another file

sy :- #cp (options) old file name to new file name

Options:-

-i → interactive (prompt and wait for confirmation before proceeding)

-r → recursively copy a directory

LINUX BASICS MATERIAL 10 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

# cp 1 2 

# cp -i 2 

Overwrite 2 ?

This the most widely used command in Unix or Linux. “ls” command is used to list the contents of a
directory. Learn the power of ls command to make your life easy. The syntax of ls command is

ies
ls [options] [pathnames]

og
To display the hidden files and directories in the current directory use the -a option of the ls command.

ol
hn
# ls -a
. .. documents .hidden_file sum.pl

c
Te
Hidden files are the one whose name starts with dot (.). The ls -a displays the current directory (.) and
parent directory (..) also. If you want to exclude the current directory, parent directory, then use -A option.
ai

# ls -A
eS

documents .hidden_file sum.pl


re

2. Write a Unix/Linux ls command to classify the files with special characters


Sh

The -F option to ls command classifies the files. It marks the

 Directories with trailing slash (/)

 Executable files with trailing asterisk (*)

 FIFOs with trailing vertical bar (|)

 Symbolic links with trailing at the rate sign (@)

 Regular files with nothing

# ls -F
documents/ sum.pl link@

LINUX BASICS MATERIAL 11 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

The -1 option to the ls command specifies that each file should be displayed on a separate line

# ls
documents
sum.pl

ies
In some cases, you want to know the inode number of a file. Use -i option to the ls command to print the

og
inode number of a file.

ol
# ls -i

hn
10584066 documents
3482450 sum.pl

c
Te
The -l option provides lots of information about the file type, owner, group, permissions, file size, last
modification date.
ai
eS

# ls –l1
total 16
re

drwxr-xr-x 2 matt db 4096 Jan 30 23:08 documents


-rw-r--r-- 1 matt db 49 Jan 31 01:17 sum.pl
Sh

 The first character indicates the type of the file. - for normal file, d for directory, l for link file and s
for socket file

 The next 9 characters in the first field represent the permissions. Each 3 characters refers the read
(r), write (w), execute (x) permissions on owner, group and others. - means no permission.

 The second field indicates the number of links to that file.

 The third field indicates the owner name.

 The fourth field indicates the group name.

 The fifth field represents the file size in bytes.

LINUX BASICS MATERIAL 12 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

 The sixth field represents the last modification date and time of the file.

 And finally the seventh field is the name of the file.

The -t option allows the ls command to sort the files in descending order based on the modification time.

ies
# ls -t1
sum.pl
documents

og
The -r option reverses the order of the files displayed. Combine the -t and -r options to sort the files in

ol
ascending order.

hn
# ls -rt1
documents
c
Te
sum.pl

So far the ls command prints the files in the current directory. Use the -R option to recursively print the files
ai

in the sub-directories also.


eS
re

# ls -R
.:
Sh

documents sum.pl
./documents:
file.txt

You can pass a directory to the ls command as an argument to print for the files in it.

# ls /usr/local/bin

LINUX BASICS MATERIAL 13 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

The -x option specifies the ls command to display the files in columns.

# ls -x

ies
Prefix Description

og
- Regular file, such as an ASCII text file, binary executable or hard link.

ol
B Block special file. Block input/output device file such as a physical hard drive.

hn
C Character special file. Raw input/output device file such as a physical hard drive

D Directory file that contains a listing of other files and directories.

L c
Symbolic link file. Links on any regular file.
Te
P Named pipe. A mechanism for interprocess communications
ai

S Socket used for interprocess communication.


eS

Ls : It displays list of files and directories


re
Sh

File type Permission Link Username Group Size of bytes Date Filename

- rwxrwxrwx 2 shree sai 560 Nov 3 1:30pm sample

D rwxrwxrwx 3 Shree sai 700 Mar 2 1:00am Pungki

WILD CARD CHARACTERS (OR) META CHARACTERS:

* ? [] -

LINUX BASICS MATERIAL 14 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

COMMANDS DESCRIPTION

ls a* It displays all file, starting letter is a.

ls b*k It displays all files starting letter is b and

ending letter is k.

ls *k It displays all files ending letter is k.

ies
ls a?k It displays all three length files names but starting

letter is a..

og
ls b??k It displays all 4 length filenames but starting letter

is b and ending letter is k.

ol
ls [aeiou]* It displays all files whose first character is anything

hn
other than a vowel

ls [k-v] It displays all field whose starting letter is between k

c
and v
Te
ai

3 Tr : It translates character by character.


eS

Examples:-
# cat > sample
re

I wisdom is, reputed institute …


Ctrl +d to save the file….
Sh

#tr “ aeiou” “AEIOU” < sample


O|p: I wisdom Is, reputed wOrd….

it replace lowercase vowel characters to uppercase vowel characters in a sample file

# tr “[a-z]” “[A-Z]” < sample


O|p: I WISDOM IS, REPUTED WORD.

Converts lower case into uppercase letters

LINUX BASICS MATERIAL 15 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

#tr “,” “\t” <emp

It replaces comma (,) delimiter with tab delimiter in emp file

#tr –d “e” < sample

ies
O|p: I wisdom is rputd word….

It deletes ‘e’ character from a sample file

og
#tr –d “aeiou” < sample

ol
O|p: wzdm s rptd nsttt….

hn
It deletes lower case “aeiou” vowel characters from sample file

#tr -s “ ” < sample


c
Te
It squeezes space character from sample
ai

Cut: it is used for to extract specified fileds and characters from a given file….
eS

#cut -f 2, 3 stud
re

It displays 2nd, 4th fields from stud file.


Sh

#cut -f 2-3 stud

It display 2nd field to, 3rd fields from stud file.

#cut -f 3- stud

It displays 3rd fields to last field from stud file.

#cut -d “;” -f 2, 4 stud

It displays 2nd & 4th fields from emp file.

LINUX BASICS MATERIAL 16 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

#cut -c 1-10 stud

It displays every line 1st character to 10th character from stud file.

#cut -c 5-10, 15-20 studs

ies
It displays every 5th character to 10th character and 15th charcter to 20th character from stud file.

og
LINK FILES:

ol
A link is not a kind of file but instead is a second name for a file. When a file had two links it is not

hn
physically present at two places, but can be referred to by either of the names. This is very useful future.If

you accidentally delete a file with a single link or a single name, there is no bringing it back, as Unix has?

c
links your file is safe even if one of the links sets several. A link is severed when the file is deleted.
Te
The concept of having several links to a file offer another advantage, if one file is to be shared b/n several

users; instead of giving each user a separable copy of the same file we LAN create links of this file in each
ai

user’s directory. This avoids unnecessary duplication of the same file contents in different directories.
eS

$ln samples my sample

The above command establishes one more link for the file sample in the form of the name my sample
re

SYMBOLIC LINKS

Links can be used to assign more than one name to a file, but they have some important limitations. They
Sh

cannot be used to assign a directory more than one name. And they cannot be used to lik filenames on

different computers.

These limitations can be eliminated using symbolic links. A symbolic link is a file that only contains the

name of another file. Then the operating system operates on a symbolic links can assign more than one

name to a file, and they can assign more than one name to a directory.

LINUX BASICS MATERIAL 17 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

The ln command can link files within a single file system. You can also link files across file systems using the

–s(symbolic) option to ln. The following example shows show you could use this feature to link a file in the

/var file system to an entry in one of your directories within the /home file system.

ln –s /var/x/docs/readme temp/x.readme

In addition to allowing links across file system, symbolic links enable you to link directories as well as

ies
regular files.

WHAT IS A PATH?
A path is a unique location to a file or a folder in a file system of an OS. A path to a file is a combination of

og
/ and alpha-numeric characters.

ol
WHAT IS AN ABSOLUTE PATH?

An absolute path is defined as the specifying the location of a file or directory from the root directory(/). In

hn
other words we can say absolute path is a complete path from start of actual filesystem from / directory.

Some examples of absolute path:


c
Te
/var/ftp/pub

/etc/samba.smb.conf
ai

/boot/grub/grub.conf

If you see all these paths started from / directory this is a root directory for every Linux/Unix machines.
eS

WHAT IS THE RELATIVE PATH ?

Relative path is defined as path related to the present working directory(pwd). Suppose I am located in
re

/var/log and I want to change directory to /var/log/kernel. I can use relative path concept to change
Sh

directory to kernel

changing directory to /var/log/kernel by using relative path concept.

pwd

/var/log

cd kernel

Note: If you observe there is no / before kernel which indicates it's a relative directory to present working

directory.

Changing directory to /var/log/kernel using absolute path concept.

LINUX BASICS MATERIAL 18 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

cd /var/log/kernel

Note: We can use an absolute path from any location where as if you want to use relative path we should

be present in a directory where we are going to specify relative to that present working directory.

Examples of relative path and absolute path for the same operation.

ies
Example1: Present location is /abc/xyz, I am want to remove /abc/xyz/read/hello.txt file.

Using relative path:

og
rm read/hello.txt

Using absolute path:

ol
rm /abc/xyz/read/hello.txt

hn
Example2: My present location is /etc/samba and now I want to change directory to /etc.

Using relative path:

c
Te
cd ..

Using absolute path:


ai

cd /etc
eS

Example3: My present location is /var/ftp/ and I want to change the location to /var/log

Using relative path:


re

cd ../log

Using absolute path:


Sh

cd /var/log

Example4: My present location is /etc/lvm and I want to change my location to /opt/oradba

Using relative path:

cd ../../opt/oradba

Using absolute path:

cd /opt/oradba

LINUX BASICS MATERIAL 19 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

Example5: My present location is /usr/local and I want to remove a abc.txt file located in this directory how

can I do that?

Using relative path:

rm abc.txt

Using absolute path:

ies
rm /usr/local/abc.txt

I hope this helps to understand the difference between Absolute and relative path.

og
FILE PERMISSIONS

ol
File ownership is an important component of UNIX that provides a secure method for storing files. Every

hn
file in UNIX has the following attributes:

 Owner permissions: The owner's permissions determine what actions the owner of the file can perform on
the file. c
Te
 Group permissions: The group's permissions determine what actions a user, who is a member of the group
that a file belongs to, can perform on the file.
ai

 Other (world) permissions: The permissions for others indicate what action all other users can perform on
the file.
eS

The Permission Indicators:


While using ls -l command it displays various information related to file permission as follows:
re

$ls -l /home/pungki
-rwxr-xr-- 1 pungki users 1024 Nov 2 00:10 myfile
Sh

drwxr-xr--- 1 pungki users 1024 Nov 2 00:10 mydir

Here first column represents different access mode ie. permission associated with a file or directory.

The permissions are broken into groups of threes, and each position in the group denotes a specific
permission, in this order: read (r), write (w), execute (x):

 The first three characters (2-4) represent the permissions for the file's owner. For example -rwxr-xr--
represents that onwer has read (r), write (w) and execute (x) permission.
 The second group of three characters (5-7) consists of the permissions for the group to which the file
belongs. For example -rwxr-xr-- represents that group has read (r) and execute (x) permission but no write
permission.

LINUX BASICS MATERIAL 20 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

 The last group of three characters (8-10) represents the permissions for everyone else. For example -rwxr-
xr-- represents that other world has read (r) only permission.

File Access Modes:


The permissions of a file are the first line of defense in the security of a Unix system. The basic building
blocks of Unix permissions are the read, write, and execute permissions, which are described below:

1. Read:

ies
Grants the capability to read ie. view the contents of the file.

2. Write:

og
Grants the capability to modify, or remove the content of the file.

ol
3. Execute:

hn
User with execute permissions can run a file as a program.

Directory Access Modes:

c
Directory access modes are listed and organized in the same manner as any other file. There are a few
Te
differences that need to be mentioned:
ai

1. Read:

Access to a directory means that the user can read the contents. The user can look at the filenames inside
eS

the directory.

2. Write:
re

Access means that the user can add or delete files to the contents of the directory.
Sh

3. Execute:

Executing a directory doesn't really make a lot of sense so think of this as a traverse permission.

A user must have execute access to the bin directory in order to execute ls or cd command.

Changing Permissions:
To change file or directory permissions, you use the chmod (change mode) command. There are two ways
to use chmod: symbolic mode and absolute mode.

Using chmod in Symbolic Mode:

LINUX BASICS MATERIAL 21 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

The easiest way for a beginner to modify file or directory permissions is to use the symbolic mode. With
symbolic permissions you can add, delete, or specify the permission set you want by using the operators in
the following table.

Chmod operator Description

+ Adds the designated permission(s) to a file or directory.

ies
Removes the designated permission(s) from a file or
-

og
directory.

ol
= Sets the designated permission(s).

hn
Here's an example using testfile. Running ls -1 on testfile shows that the file's permissions are as follows:

$ls -l testfile
c
Te
-rwxrwxr-- 1 pungki users 1024 Nov 2 00:10 testfile

Then each example chmod command from the preceding table is run on testfile, followed by ls -l so you
ai

can see the permission changes:


eS

$chmod o+wx testfile


$ls -l testfile
-rwxrwxrwx 1 pungki users 1024 Nov 2 00:10 testfile
re

$chmod u-x testfile


$ls -l testfile
Sh

-rw-rwxrwx 1 pungki users 1024 Nov 2 00:10 testfile


$chmod g=rx testfile
$ls -l testfile
-rw-r-xrwx 1 pungki users 1024 Nov 2 00:10 testfile

Here's how you could combine these commands on a single line:

$chmod o+wx,u-x,g=rx testfile


$ls -l testfile
-rw-r-xrwx 1 pungki users 1024 Nov 2 00:10 testfile

Using chmod with Absolute Permissions:

LINUX BASICS MATERIAL 22 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

The second way to modify permissions with the chmod command is to use a number to specify each set of
permissions for the file.

Each permission is assigned a value, as the following table shows, and the total of each set of permissions
provides a number for that set.

Number Octal Permission Representation Ref

ies
0 No permission ---

og
1 Execute permission --x

ol
2 Write permission -w-

hn
3 Execute and write permission: 1 (execute) + 2 (write) = 3 -wx

4 Read permission c r--


Te
5 Read and execute permission: 4 (read) + 1 (execute) = 5 r-x
ai

6 Read and write permission: 4 (read) + 2 (write) = 6 rw-


eS

7 All permissions: 4 (read) + 2 (write) + 1 (execute) = 7 rwx


re

Here's an example using testfile. Running ls -1 on testfile shows that the file's permissions are as follows:
Sh

$ls -l testfile
-rwxrwxr-- 1 pungki users 1024 Nov 2 00:10 testfile

Then each example chmod command from the preceding table is run on testfile, followed by ls -l so you
can see the permission changes:

$ chmod 755 testfile


$ls -l testfile
-rwxr-xr-x 1 pungki users 1024 Nov 2 00:10 testfile
$chmod 743 testfile

LINUX BASICS MATERIAL 23 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

$ls -l testfile
-rwxr---wx 1 pungki users 1024 Nov 2 00:10 testfile
$chmod 043 testfile
$ls -l testfile
----r---wx 1 pungki users 1024 Nov 2 00:10 testfile

Changing Owners and Groups:

ies
While creating an account on Unix, it assigns a owner ID and a group ID to each user. All the permissions
mentioned above are also assigned based on Owner and Groups.

og
Two commands are available to change the owner and the group of files:

ol
1. chown: The chown command stands for "change owner" and is used to change the owner of a file.
2. chgrp: The chgrp command stands for "change group" and is used to change the group of a file.

hn
Changing Ownership:

The chown command changes the ownership of a file. The basic syntax is as follows:

c
Te
$ chown user filelist

The value of user can be either the name of a user on the system or the user id (uid) of a user on the
ai

system.
eS

Following example:

$ chown pungki testfile


re

$
Sh

Changes the owner of the given file to the user pungki.


NOTE: The super user, root, has the unrestricted capability to change the ownership of a any file but
normal users can change only the owner of files they own.

Changing Group Ownership:

The chrgp command changes the group ownership of a file. The basic syntax is as follows:

$ chgrp group filelist

The value of group can be the name of a group on the system or the group ID (GID) of a group on the
system.

Following example:

LINUX BASICS MATERIAL 24 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

$ chgrp special testfile


$ Changes the group of the given file to special group

Vi EDITOR
Compared to ed or ex and vi editor is head and shoulders above them in almost every way. It is a screen

ies
editor rather than a line editor; it shows you as much of the file as it can fit on the screen. Vi is case-

sensitive .vi is available on almost all unix system.

og
Mode of operations

ol
The vi program has three nodes of operation:

hn
1) command mode:

This is the default mode in this mode all the keys pressed by the user are interpreted to be editor
commands
c
Te
2) Insert mode

This mode permits insertion of new text, editing of existing text or replacement of existing text.

3) The ex command mode:


ai

This mode permits us to give commands at the command line. The bottom line of the vi screen is
eS

called the command line. VI uses the command line to display messages and commands .All
commands entered in the ex command mode ared displayed in the command line. This mode is

so called because commands given in this mode are compatible with the commands of the ex
re

editor.
Sh

Command mode commands


Commands for to shift command mode into insert mode

Command Function
A It places cursor at end of the current line
A It places cursor right side of the cursor position
I It places cursor at beginning of the current line
I It places cursor left side of the cursor position
O Enters text input mode by opening a new line immediately
below the current line
0 Enters text input mode by opening a new line immediately

LINUX BASICS MATERIAL 25 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

above the current line


R Enter text input mode and overwrites from current cursor
poition onwards

To edit your text,you need to move the cursor to the point on the screen where you will begin the

ies
correction. This is easily done with four keys h,j,k and l.

H Move the cursor one character to the left

og
I Move the cursor one character to the right
J Move the cursor down on line

ol
K Move the cursor up on line

hn
Positioning by character

c
Te
Command Function
H Moves the cursor one character to the left.
ai

Backspace Moves the cursor one character to the left.


L Move the cursor one character to the right
eS

Space bar Move the cursor one character to the right


0 Moves the cursor to the beginning of the current line.
re

$ Move the cursor to the end of the current line


Sh

Positioning by line

Command Function
J Moves the cursor down one line from it’s present
K Moves the cursor up one line from it’s present position in the
sample column
+ Moves the cursor down to the beginning of next line.
- Moves the cursor upto the beginning of previous line.
Enter Moves the cursor down to the beginning of the next line.

LINUX BASICS MATERIAL 26 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

Positioning by word

Command Function
W Move the cursor to the right, to the first character of the next word
B Move the cursor back to the first character of the previous word.
E Move the cursor to the end of the current word.

ies
og
Positioning in the window

Command Function

ol
H Moves the cursor to the first line on the screen, or “Home”
M Moves the cursor to the middle line on the screen

hn
L Moves the cursor to the last line on the screen

c
Te
Commands for positioning in the file
ai

Scrolling
eS

Commands Function
Ctrl f Scrolls the screen forward a full window, revealing the window
re

of text below the current window.


Ctrl b Scrolls the screen back a full window, revealing the window of
Sh

text above the current window.

Command for deleting text

Commands Function
X Deletes the character at current cursor position
X Deletes the character to the left of the cursor
Dw Deletes a word(or part of a word) from the cursor to the next
space or to the ext punctuation.
Dd Deletes the current line.
Nx,ndw,ndd Deletes n characters, n words or nlines.

LINUX BASICS MATERIAL 27 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

D0 Deletes the current line from the cursor to the beginning of the
line.
D$ Deletes the current line from the cursor to the end of the line.

Commands for copying and paste text

ies
Commands Function
Yw Yank word from cursor position
Yy Yanks line from cursor position

og
Y$ Yanks line from cursor position of line
Y0 Yanks line from cursor position to beginning of line

ol
P Pastes last yanked buffer

c hn
Te
Commands for quitting vi
ai

Command Function
Zz Writes the buffer to the file and quits vvi
eS

:wq Writes the buffer to the file and quits vi


:w filename and :q Writes the buffer to the filename(new) and quits vi
:w! filename and :q Overwrites the existing filename with the contents of the buffer and
re

quits vi.
:q! Quits vi whether or not changes made to the buffer were written to a
Sh

file. Does not incorporate changes made to the buffer since the last
write(:w) command
:q Quits vi changes made to the buffer were written to a file
Set nu Setting line numbers for file
Set nonum Removing line numbers

LINUX BASICS MATERIAL 28 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

FIND FILES
The find command help s you locate files in the file system. with the find commands you can search
through any part of the filesystem. Looking for all files with a particular name. It is extremely powerful, and

at times it can be a lifesaver , but it is also rather difficult to remember and to use.

An example of an common problem that find can help solve is locating a file that you have misplaced for
example, if you want to find a file called sai but you can’t remember where you put it , you can use find to

ies
search for it through all or part of your directory system.

The find command searches through the contents of one or more directories including all of their sub

og
directories. You have to tell find in which directory to start its search. To search through all your directories,

for example, tell find to start in your login directory.

ol
find command can find files according to

hn
1) File names

c
Te
2) File types

3) Permissions
ai

4) Owners
eS

5) Modified date and time


re

6) Size
Sh

SEARCH USING FIND COMMAND


FIND FILES WITH NAME
Syntax:
find path options filename
Example1: find all the files in /home with name test.txt. Here –name is used to specify the filename.
find /home –name test.txt
Example2: find the files whose name is test.txt and in present working directory
find . –name test.txt
Or

find –name test.txt

LINUX BASICS MATERIAL 29 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

Example3: find all the files whose name contains both capital letters and small letters in it.
find /home –iname test.txt
-iname option is used to mention ignore the case sensitivity of a file.
Search for files depending on their File types:

Example4: Search for only directories whose name is var in / directory


find / -type d –name var

ies
Example5: Search for an mp3 files whose name is temp.mp3
find / -type f –name temp.mp3
Below are the file types supported by find command, to know more about file types in Linux/Unix please

og
have a look at our other post on File types.
Sl.no Symbol Type

ol
1 F Regular file
2 D Directory file

hn
3 B Block file
4 C Character file
5 P
c Pipe file
Te
6 L Symbolic link file
7 S Socket file.
ai

SEARCH FOR FILES DEPENDING ON THEIR PERMISSIONS


eS

Example6:Search for a file name test.txt and its permissions are 775 in a given box
find / -perm 775 –name test.txt
re

Example7: How about searcing files with SUID bit set and file permissions are 755?
find / -perm 4755
Sh

Example8:How can i find SGID bit set files with 644 permissions?
find / -perm 2644
Example9: How can i find Sticky bit set files in my system with permissions 551?
find / -perm 1551
Example10:Search for all the files whose SUID bit is set
find / -perm /u=s
Example11: Search for all the files whose SGID bit is set
find / -perm /g+s
Note: We can use = or + interchangeably to check if a permissions is set or not as shown in above two
examples.
Example12: Search for all the files whose StickyBit is set

LINUX BASICS MATERIAL 30 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

find / -perm /o=t


Example13: Search for all the files whose owener permissions is read only.
find / -perm /u=r
Example14:Search for all the files which have user, group and others with executable permissions
find / -perm /a=x
To know about more on the permissions you have look at our other posts on chmod command.
Search according to Owners and group owners.

ies
Example15: Search for all the files with name test.txt and the owner of this file is Surendra
find / -user Surendra –name test.txt
Example16: find all the files whos name is test.txt and owned by a group called redcluster

og
find / -group redcluster –name test.txt
to know more about owners and groups you have to look at our previous post on chown command.

ol
SEARCH ACCORDING TO MODIFIED DATE AND TIME.

hn
What is ctime, atime, and mtime?

c
It is important to distinguish between a file or directory's change time (ctime), access time (atime), and
Te
modify time (mtime).

CTIME -- In UNIX, it is not possible to tell the actual creation time of a file. The ctime--change time--is the
ai

time when changes were made to the file or directory's inode (owner, permissions, etc.). The ctime is also
eS

updated when the contents of a file change. It is needed by the dump command to determine if the file
needs to be backed up. You can view the ctime with the ls -lc command.
re

ATIME -- The atime--access time--is the time when the data of a file was last accessed. Displaying the
contents of a file or executing a shell script will update a file's atime, for example. You can view
Sh

the atime with the ls -lu command.

MTIME -- The mtime--modify time--is the time when the actual contents of a file was last modified. This is
the time displayed in a long directoring listing (ls -l).

In Linux, the stat command will show these three times.

Examples

$ cat file
file's atime is updated.
$ chmod g+w file

LINUX BASICS MATERIAL 31 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

file's ctime is updated.

$ echo "File contents" >> file

file's ctime and mtime are updated.

Below is the matrix which give you brief idea on how to search according to modified date,

ies
accessed date etc.

og
SL. NO -CTIME -MTIME -ATIME
+90 File status changed more Modified more than 90 Accessed more than 90

ol
then 90 days back days back days back
90 File status changed exactly Modified exactly 90 days Accessed exactly 90 days

hn
90 days back back back
-90 File status changed less Modified less than 90 days Accessed less than 90
than 90 days
c days back
Te
Example17: Search for a file: test.txt whose file status is changed more than 90 days back
find / -ctime +90 –name test.txt
Example18: Search for all the files which are modified exactly 90 days back
ai

find / -mtime 90
Example19: Search for all the files with name test.txt which is accessed less than 90 days
eS

find / -atime -90


Example20: find all the files which are modified more than 90 days back and less than 180 days
find / -mtime +90 –mtime -180
re

Below is the matrix which gives you brief idea on how to search according to modified time, accessed time
Sh

in minutes etc.

SL. NO -CMIN -MMIN -AMIN


+30 File status changed more Modified more than 30 Accessed more than 30
then 30 mins back mins back mins back
30 File status changed exactly Modified exactly 30 mins Accessed exactly 30 mins
30 mins back back back
-30 File status changed less Modified less than 30 Accessed less than 30
than 30 mins mins mins
Example21: find all the files changed less than 30mins
LINUX BASICS MATERIAL 32 www.shreesaitechnologies.com
040-23752633 LINUX BASICS MATERIAL

find / -cmin -30


Example22: find all the files modified exactly 30 mins back
find / -mmin 30
Example23: find all the files accessed more than 30 mins back
find / -amin +30
Example24: find all the files which are modified more than 5mins back and less than 25mins
find / -mmin +5 –mmin -25

ies
Example25: I have new file called test.txt which is just created, now I want to get all the files which are
created later this file creation.
find / -newer test.txt

og
ol
SEARCH FOR FILES/FOLDERS DEPENDING ON THE SIZE WITH –SIZE OPTION

c hn
Te
SL.NO +10 10 -10
c for bytes(8 bits) Search for files more Search for files Search for files less
than 10c size exactly 10b size than 10b size
ai

k for kilobytes Search for files more Search for files Search for files less
than 10k size exactly 10k size than 10k size
eS

M for Megabytes Search for files more Search for files Search for files less
than 10M size exactly 10M size than 10M size
re

G for Gigabytes Search for files more Search for files Search for files less
than 10G size exactly 10G size than 10G size
Sh

Example26: Search for files whose size is more than 10bytes


find / -size +10c
Example27: Search for files which are exactly 10kb in /opt folder
find /opt –size 10k
Example28: Search for files which are less than 10MB in /var folder
find /var –size -10M
Example29: Search for files which are more than 1GB size in /usr folder
find /usr –size +1G
Example30: find all the empty files in my system
find / -size 0k

LINUX BASICS MATERIAL 33 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

AWK
Awk is one of the most powerful tools in Unix used for processing the rows and columns in a file. Awk

supports most of the operators, conditional blocks, and loops available in C language.

ies
SYNTAX:-
awk options 'selection-criteria {action}' files(s)

og
awk '/abc/{print}' test
Prints lines containing abc

ol
awk '/^unix/{print}' test

Print all lines starting with unix.

hn
awk -F: '$3 /^0$/' /etc/passwd

Print users having uid 0


c
Te
awk -F: '{ print $1,$2,$3 }' /etc/passwd If selection criteria is missing, the action applies to all fields.
ai

AWK has several built-in variables.


eS

NR - Record Number
re

FS - Fields Seperator

NF - Number of Fields
Sh

Rs - Record Seperator

awk '{ print "Record No", NR, "has", NF, "fields"}' emp.list

COMPARISON AND LOGICAL OPERATORS


awk 'NR == 1,NR == 5 {print}' test
Prints lines from 1 to 5

awk -F: 'NR == 3,NR==6 { print NR,$2,$3,$6}' emp.list


Prints Record Number,1,3,7 fields from /etc/passwd file between the lines 3 to 6.

LINUX BASICS MATERIAL 34 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

awk '$6>5000 {print}' test

Prints 6th field if value greater than 5000

awk -F: '$3>200 {print $1,$3}' /etc/passwd


Prints all username, uid having uid>200

ies
awk '$3 == "director" || $3 == "manager" {print}' emp.list

awk 'NR > 5 && NR < 10 { print }' emp.list


Record number 6 to 9

og
awk -F: '($3 > 1 && $3 < 4 ) || ($3 >=7 && $3 <=10 )' /etc/passwd

ol
hn
POSITIONAL PARAMERS
A shell script uses special parameters like $1,S2 etc to represent command line arguments. But awk uses

c
the same parameters as field identifiers. To distinguish between shell parameter and field identifier quoting
Te
will be used for positional parameters.
ai

awk -F: '$3 > '$1' {print}' /etc/passwd


eS

Matching Pattern
For matching regular expression with a field, awk uses ~ operator and !~ negates the match
re

awk -F: '$1 ~ /root/' /etc/passwd


Sh

CONTROL STATEMENTS
awk supports conditional structures (if) and loops (while and for).

The if statement in awk takes this form:

if ( condition ) {
statements

}
else {

statements

LINUX BASICS MATERIAL 35 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

awk -F: '{ if ( $3 > 100 ) { print $1,$3 } else { echo "Not Found" } }' /etc/passwd

while
-----

ies
while ( condition ) {
statements

og
}

ol
for

hn
----

for ( initialization; condition; loop counter ) {


c
Te
statements

}
ai

or
eS

for ( variable in value ) {


re

statements

}
Sh

FUNCTIONS
awk has several built-in functions, performing both arithmetic and string operations.

ARITHMETIC

int(x) Returns integer value of x


sqrt(X) Returns square root of x

STRING

length() Returns length of complete line

LINUX BASICS MATERIAL 36 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

length(X) Returns length of x

tolower(x) Convert string x to lowercase


toupper(x) To uppercase

substr(str,n) Returns remaining string from position n in string str


index(s1,s2) Returns position of string s2 in string s1

ies
awk -F: '{print length()}' /etc/passwd

awk -F: '{print substr($1,2)}' /etc/passwd

og
From a file

ol
cat > emp.awk

hn
$3 == "director" && $6 > 12000 { printf "%4d %-20s %-12s %d\n", ++kount, $2,$3,$6}

awk -F: -f emp.awk emp.list


c
Te
ai

SED (STREAM EDITOR)


eS

sed combines the work of several filters.


re

Syntax
Sh

sed options 'address action' file(s)

address - location of data

action - action to perform on data

commands

i,a insert, append text

d delete line(s)

LINUX BASICS MATERIAL 37 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

p print line(s) on standard output

q quits after reading upto address line

r file place contents of file after lines

ies
w file writes addressed lines to the file

og
s/s1/s2 Replaces first occurence of s1 in all lines with s2

ol
s/s1/s2/g Replaces all occurences

hn
Ex:-
---
c
Te
sed '1,4d' test Remove 1 & 4 lines from the file test
ai

sed '10q' test Quits after reading 10 lines


eS

sed '1,$p' test Prints line 3 to end


re

sed 's/linux/unix/g' test Replaces linux with unix


Sh

sed '10,20 s/linux/unix/g' test Replace linux with unix in lines 10 to 20

sed '/begin/,/end/' test Print line containing begin throught line containing end

sed -e '1,2p' -e '9,10p' test Prints lines 1,2 and 9,10

ls -l | sed -n '/^.....w/p' To list files having write permission for group

sed '1i\

LINUX BASICS MATERIAL 38 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

>abc\

>xyz' test Inserts text at line1

sed 'a\

' test Inserts blank lines after each line

ies
sed '/^#/d' test Delets comments

og
ol
COMMUNICATION COMMANDS
The write command:

hn
The write command can be used by any user to write something on someone else’s terminal,

provide the receipt of the message permits communication.


c
Te
$ write techno2

Hey there | I am back from Guntur.


ai

Just want to say hello….


eS

Ctrl d
re

There are two prerequisites for a smooth write operation:

a) The recipient must be logged in, else an error message is inevitable.


Sh

b) The recipient must have given permission for message to reach his or her terminal. This is done by
saying at the $prompt

$mesg -y

If you are expecting nothing of consequence and do not wish to be disturbed by social trivial like the one

we just saw. You can deny write permission to your terminal by saying

$mesg -n

A superuser however can write to any terminal, irrespective of whether mesg has been set –y or –n

LINUX BASICS MATERIAL 39 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

Mail command:-

Using mail you can quickly and efficiently circulate memos and other written information to your co-
workers . You can even send and reeive mail from people outside your organization if you and they use
network computers. Mail can be sent to users who have logged in currently or even to users who haven’t
logged in currently in case the user has logged in at several terminals the moment mail is sent to this user

ies
it becomes available at all the terminals.

Sending mail:

og
$mail techno1

Subjet: from shree sai tehnologies

ol
Hello,

hn
How r u?

c
Shree sai technologies offering unix course with less fees.
Te
Ctrl + d
ai

To send the same mail to more than one user, you can say
eS

$mail sree hari krishna

Subject: From shree sai technologies


re

Hello,
Sh

How are you?

Shree sai technologies offering unix course with less fees.

Ctrl d

If you are to mail a program written by you and then you of course can not be expected to type in the
program after you have issued the mail. Commad as in the above case. In such cases . In such cases yu can

use input redirection as shown below

$mail shree hari krishna

LINUX BASICS MATERIAL 40 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

Handling Incoming Mail

To read the mail that has been received we simply say mail at the shell prompt.

$mail

&

ies
The output shows that there are 3 messages in our mailbox of which I has been received since we logged

in whereas 2 were lying in the mail box unread even before we logged in. the N or a U in the first column
indicates just this.Each message present in the mail box is given a number. This members are shown in the

og
second column . The > sign indicates that the current message is message umber 3. Followd by this is the
logname of the person who sent the mail, the date and time when the mail was received as well as the

ol
subject of each message.

hn
Observe the & displayed at the bottom. This is known as the mail prompt. We can use several commands
at this prompt if you want to know which, you can type a / and obtain help on these commands. Let us

c
now view the seond message. Just type a 2 at the & prompt.
Te
&2
ai

It displays second message on the output screen


eS

To view third message just type a 3 at the & prompt

&3
re

It displays third message on the output screen


Sh

Finally, we exit from the mail command by typing q at the & prompt.

&q

This implies that out of the three messages we have recived we have hone through 2 messages hence they
have been removed from out primary mailbox file user/spool/mail/aa12 and appended to the secondary
mail box file/user/aa12/mbox. One message will remains unread is still lying in the primary mailbox file. If

we invoke mail once again we would be shown only the one unread message. What if we want to review

the message transferred to the secondary mailbox? Simply invoke the mail command as show below.

$mail –f

LINUX BASICS MATERIAL 41 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

The following table shows the operations that you can perform on mail messages.

COMMAND ACTION
+ or return Print next message
- Print previous message
# Print number of urrent message
D Delete the message

ies
Dq Delete the message and quit
M person Mail this message to person(your own login name is
the default if person is not specified)

og
P Print current message again
Q or CTRL-D Put undeleted mail back in /var/mail/shree,and quit

ol
uN Undeleted message N
S file Save this message. $usr/mbox is used as a default if

hn
file is not specified.
W file Save the mail back .m mail file and quit
X
c Put all mail back in mail file and quit
Te
!command Escape to the shell and run command
? Print summary of mail command
Input/output redirections
ai

In all operating system, there is a standard input device and standard output device in unix, as also in most
eS

other operating systems, the standard input device is keyboard and the standard output is the display

screen
re

Special files that instruct all the programs to accept standard input from the keyboard and direct the

standard output to the display, are provided by Unix. The three streams, i.e. the standard input, standard
Sh

output and standard error are denoted by the numbers 0,1 and 2 respectively.

Stream Device Value


Standard input Keyboard 0
Standard output Terminal screen 1
Standard error Terminal screen 2
Unix , allows you to change the standard input and output temporarily by using what is known as

redirection and piping.

Sometimes it is useful to redirect the input or output to a file or a printer. For example, you might want to

redirect a directory listing from the screen to a file. Unix provides redirection symbols for the purpose.

LINUX BASICS MATERIAL 42 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

 The symbol “>” implies redirection of output and the symbol implies redirection of input.

 The symbol”> “sends the output of a command to a file or a device, such as a printer.
 The symbol”< “talks the input needed for a command from a file rather than from the keyboard.

 The symbol”>>” adds output from a command to the end of a file without deleting the

information already in the file.

ies
Piping :-

The unix piping facility let us connect commands to other commands. This facility is of utmost importance

in combining Unix commands and other operations. It can be really useful to redirect the output of one

og
program so that it becomes the input of another program, thereby joining of two programs. To send the
output of one command as input for another, the two commands must be joined using a pipe(|)

ol
characters.

hn
PROCESS MANAGEMENT
c
This is a very basic ps usage. Just type ps on your console to see its result.
Te
ai
eS

By default, it will show us 4 columns of information.


re

 PID is a Process ID of the running command (CMD)


Sh

 TTY is a place where the running command runs


 TIME tell about how much time is used by CPU while running the command
 CMD is a command that run as current process
This information is displayed in unsorted result.

Show all current processes

To do this, we can use -a options. As we can guess, -a is stand for “all”. While x will show all process even
the current process is not associated with any TTY (terminal)

$ ps -ax

This result might be long result. To make it more easier to read, combine it with less command.

LINUX BASICS MATERIAL 43 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

$ ps -ax | less

ies
og
ol
c hn
Te
Filter processes by its user
ai

For some situation we may want to filter processes by user. To do this, we can use -u option. Let say we
want to see what processes which run by user Pungki. So the command will be like below
eS

$ ps -u Pungki
re
Sh

Filter processes by CPU or memory usage

Another thing that you might want to see is filter the result by CPU or memory usage. With this, you can
grab information about which processes that consume your resource. To do this, we can use aux options.
Here’s an example of it :

LINUX BASICS MATERIAL 44 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

$ ps -aux | less

ies
og
ol
hn
Since the result can be in a long list, we can pipe less command into ps command.

c
By default, the result will be in unsorted form. If we want to sort by particular column, we can add--
Te
sort option into ps command.

Sort by the highest CPU utilization in ascending order


ai

$ ps -aux --sort -pcpu | less


eS
re
Sh

Sort by the highest Memory utilization in ascending order

$ ps -aux --sort -pmem | less

LINUX BASICS MATERIAL 45 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

ies
og
Or we can combine itu a single command and display only the top ten of the result :

ol
$ ps -aux --sort -pcpu,+pmem | head -n 10

Filter processes by its name or process ID

hn
To to this, we can use -C option followed by the keyword. Let say, we want to show processes named
getty. We can type :
c
Te
$ ps -C getty
ai
eS
re

If we want to show more detail about the result, we can add -f option to show it on full format listing. The
Sh

above command will looks like below :

$ ps -f -C getty

Filter processes by thread of process

LINUX BASICS MATERIAL 46 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

If we need to know the thread of a particular process, we can use -L option followed by its Process ID (PID).
Here’s an example of -L option in action :

$ ps -L 1213

ies
og
ol
As we can see, the PID remain the same value, but the LWP which shows numbers of thread show different
values.

hn
Show processes in hierarchy

Sometime we want to see the processes in hierarchical form. To do this, we can use -axjfoptions.
c
Te
$ps -axjf
ai
eS
re

Or, another command which we can use is pstree.


Sh

$ pstree

LINUX BASICS MATERIAL 47 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

ies
og
ol
hn
Show security information

c
If we want to see who is currently logged on into your server, we can see it using the ps command. There
Te
are some options that we can use to fulfill our needs. Here’s some examples :

$ ps -eo pid,user,args
ai

Option -e will show you all processes while -o option will control the output. Pid, User and Args will show
eS

you the Process ID, the User who run the application and the running application.
re
Sh

The keyword / user-defined format that can be used with -e option are args, cmd, comm, command,
fname, ucmd, ucomm, lstart, bsdstart and start.

Show every process running as root (real & effecitve ID) in user format

System admin may want to see what processes are being run by root and other information related to it.
Using ps command, we can do by this simple command :

$ ps -U root -u root u

LINUX BASICS MATERIAL 48 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

The -U parameter will select by real user ID (RUID). It selects the processes whose real user name or ID is in
the userlist list. The real User ID identifies the user who created the process.

While the -u paramater will select by effective user ID (EUID)

The last u paramater, will display the output in user-oriented format which contains User, PID, %CPU,
%MEM, VSZ, RSS, TTY, STAT, START, TIME and COMMAND columns.

ies
Here’s the output of the above command.

og
ol
c hn
Te
ai
eS

Use PS in a realtime process viewer


re

ps will display a report of what happens in your system. The result will be a static report.
Let say, we want to filter processes by CPU and Memory usage as on the point 4 above. And we want the
Sh

report is updated every 1 second. We can do it by combining ps command with watch command on Linux.

Here’s the command :

$ watch -n 1 ‘ps -aux --sort -pmem, -pcpu’

LINUX BASICS MATERIAL 49 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

ies
og
ol
c hn
Te
ai

If you feel the report is too long, we can limit it by - let say - the top 20 processes. We can
eS

addhead command to do it.

$ watch -n 1 ‘ps -aux --sort -pmem, -pcpu | head 20’


re
Sh

LINUX BASICS MATERIAL 50 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

ies
og
ol
c hn
Te
ai

This live reporter is not like top or htop of course. But the advantage of using ps to make live report is that
you can custom the field. You can choose which field you want to see.
eS

For example, if you need only the Pungki user shown, then you can change the command to become like
this :
re

$ watch -n 1 ‘ps -aux -U Pungki u --sort -pmem, -pcpu | head 20’


Sh

LINUX BASICS MATERIAL 51 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

ies
og
ol
c hn
Te
You may use ps on your daily usage to monitor about what happens your Linux system. But actually, you
ai

can generate various types of report using ps command with the use of appropriate paramaters.

Another ps advantage is that ps are installed by default in any kind of Linux. So you can just start to use it.
eS
re
Sh

LINUX BASICS MATERIAL 52 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

SHELL SCRIPTING
SHELL

The shell read your commands and interprets them as requests to execute a program or programs, which

it then arranges to have carried out. It is called a command interpreter .Besides being a command
interpreter; the shell is also a programming language. as a programming language it permits you to
control how and when commands are carried out. Shell acts as an interface between user and the kernel.

ies
og
KERNEL

The kernel is the part of the operating system that interacts directly with the hardware of a computer,

ol
through device drivers that are built into the kernel. It provides set of services that can be used by

hn
programs; control these programs from the underlying hardware.

The major functions of the kernel are to manage computer memory, to control access to the computer, to

c
maintain file system, to handle interrupts (singles to terminate execution).
Te
To handle errors, to perform input and output services (which allow computers to interact with terminals,
ai

storage devices, and printers). And to allocate the resources of the computer (such as the cpu or

input/output devices) among users.


eS

Programs interact with the kernel through approximately 100 system calls. System calls tell the kernel to
carry out various task for the program, such a s opening a file, writing to a file, obtaining information about
re

a file, executing a program, termination a process , changing priority of a process.


Sh

TYPES OF SHELLS

Shell Developed by Shell prompt Execution command


Bourne shell Steve Bourne $ Sh
Korn shell David korn $ Ksh
C shell Bill joy % Csh
Bash Brain fox $ Bash

LINUX BASICS MATERIAL 53 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

SHELL SUPPORT FEATURES


Sh Cshell Tshell Korn bash
Programming Yes Yes Yes Yes Yes
language
Shell variables Yes Yes Yes Yes Yes
Command alias No Yes Yes Yes Yes

ies
Command history No Yes Yes Yes Yes
File completition No Yes Yes Yes Yes
Command line No Yes Yes Yes Yes

og
editing
Job control No Yes Yes Yes Yes

ol
hn
HIGHLIGHTS OF SHELL (korn, bash, cshell)

 Use aliases to invoke commands with short names


 c
Use the history mechanism to recall, edit and run previously executed commands
Te
 Use the job control commands to switch control from one job to another
 Edit any previous command line using the vi-like in-line editing features.
ai

 Use the tilde substitution feature to shorten pathnames that refer to the home directory,
 Prevent accidental overwriting of files and login out using the set command.
eS

 Make environment settings permanent using profiles and rc.scripts


 Master the built in computing and string handling features of the korn shell.
 Learn the exclusive programming constructs of the Korn shell and essential constructs of the C Shell
re

TYPE OF VARIABLES
Sh

 USER DEFINED VARIABLES


 SYSTEM DEFINED VARIABLES

SYSTEM DEFINED VARIABLES

STYSTEM VARIABLE MEANING


PS1 primary shell prompt
PATH Defines the path which the shell must search in
order to execute command
PS2 The system prompt2,default value is “>”
HOME stored default working directory of user

LINUX BASICS MATERIAL 54 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

MAIL Defines the file where the mail of user is stored


IFS Defines the internal Field Separator which is a
space, tab or newline
SHELL Defines the name of your default shell
TZ Defines the name of the time zone in which we are
working

ies
Rules for building shell variables (user defined variables)

og
 The first character of variables name must either be alphabet or an underscore.
 variable name is any combination of alphabets, digits and underscore(-)

ol
 No commas or blanks are allowed within variable name.
 Reserved words are not allowed

hn
 Variable names are case sensitive, that is Name, NAME, name, Name are all different.

List of keywords available in Bourne shell

c
Te
Echo Until If Umask
Read Case Else Unlieval
Set Esac Fi Exec
ai

Unset Break While Wait


eS

Readonly Continue Do Trap


Shift Exit Done Eval
Export Return For
re

SHEBANG:
Sh

The #! Syntax used in scripts to indicate an interpreter for execution under Unix/Linux operating
systems . Most Linux shell and perl / python scripts start with the following lines

#! /bin/bash
Or

#! /usr/bin/perl
Or

#!/usr/bin/python

IT is called a shebang or a “bang” line.

LINUX BASICS MATERIAL 55 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

It is nothing but the absolute path to the bash interpreter.

It consists of a number sign and an exclamation pointing character (#!), followed by the full path to the
interpreter such as /bin/bash.

All scripts under Linux execute using the interpreter specified on a first line.
Almost all bash scripts often begin with #!/bin/bash(assuming that bash has been installed in /bin)
This ensures that bash will be used to interpret the script, even if it is executed under another shell.

ies
The shebang was introduced b Dennis Ritchie between version 7 and Unix 8 at bell laboratories.

If you do not specify an interpreter line. The default is usually the /bin/sh .But it is recommended that you
set #!/bin/bash line.

og
COMMENT

ol
hn
You should be aware of the fact that you might not be the only person reading your code. A lot of users
and system administrators run scripts that were written by other people. If they want to see how you did it ,
comments are useful to enlighten the reader.
c
Te
Comments also make your own life easier. Say that you had to read a lot of man pages in order to achieve
ai

a particular result with some command that you used in your script. You won’t remember how it worked if

you need to change your script after a few weeks or months, unless you have commented what you did,
eS

how you did it and / or why you did it.


re

By default shell script can be commented out prefixing # character, so if there are any lines starting with #

then those lines will be treated as comments and those will be removed at the time of executing the
Sh

scripts.

EXECUTING A SHELL SCRIPT.

The easiest way to run shell script in linux or unix is to type the following commands. Open the terminal
and type the command.

$ sh myscript.sh

Or
$ bash myscript.sh

Another recommend option is to set an executable permission using the chmod a command as follows.

LINUX BASICS MATERIAL 56 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

$ chmod +x myscript.sh

And run your shell script files as follows or you can give the full path of the file also.

$ ./myscript.sh

ies
Echo command:
The built-in echo command is an older form of printf command. Bash provides it for compatibility with

og
almost all the shells. Echo does not use a format string like printf command.

ol
It used to display the text or variables on the output screen. The following the examples narrates the usage

hn
of echo command

c
Te
TYPE OF OPERATORS
 Arithmetic operator
ai

 Relational operator
o Numeric comparison operator
eS

o String comparison operator


 Logical operator
re

Arithmetic operations

Operator Meaning
Sh

+ Addition
- Subtraction
\* Multiplication
/ Division
% Modular division
NUMERIC COMPARISON OPERATOR

Operator Meaning
-gt Greater than
-ge Greater than or equal to
-lt Less than

LINUX BASICS MATERIAL 57 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

-le Less than or equal to


-eq Equal to
-ne Not equal

STRING COMPARISION OPERATOR

ies
STRING COMPARISION OPERATOR COMPARISION
Condition Meaning
Str1=str2 True if the strings are same

og
Str1!=str2 True if the strings are different
-n string True if the length of string greater than zero

ol
-z string True if the length of string is zero
LOGICAL OPERATORS

hn
Operator Meaning
-a
c And
Te
-o Or
! Not
ai

When to use shell scripting


eS

1. Customizing your work environments. For example, every time you log in if you want to see the
current date, a welcome message and the list of users who have logged in you can write a shell
re

script for the same.


2. Automating your daily tasks. For example, you a may want to back up all your programs at the end
Sh

of day. This can be done using a shell script.


3. Automating repetitive tasks, for example, the repetitive task of compiling a program, linking it with
some libraries and executing the executable code can be assigned to a shell script.

4. ESCAPE SEQUENCE

LINUX BASICS MATERIAL 58 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

Escape sequence Significance


\a Bell
\b Backspace
\n Newline
\t Tab
\v Vertical tab

ies
\r carriage return
\ Double quotes
\’ Single quotes

og
\\ Back slash
\$ Dollar

ol
Shell variables:

hn
Variable is a data name and it is used to store value. Variable value can change during execution
of the program.

c
Te
Echo
Echo command is used to display the messages on the screen and is used to display the value
ai

stored in a shell variables.


eS

$echo “smmit Networks”


re

Smmit Networks
Sh

Note : double quotes are option in echo statement.

Ex2: $echo “today date is :`date`

Today date is sat mar 4 04:40:10 IST 2005

SHELL VARIABLE
Eg 1: $a=10

Note: there are no predefined data types in Unix. Each and every thing it treat as character. Each
character occupies 1 byte of memory.

LINUX BASICS MATERIAL 59 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

Eg 2:$b=2000

In above example a occupies 2 bytes and b occupies 4 bytes of memory

Reading of variables

$ is the operator to read variable value

ies
Eg 1:$n=100

og
$echo $n

ol
100

hn
Eg 2:$name =”smmit networks”

c
Te
Smmit networks
ai

NULL VARIABLE
eS

A variable which has been defined but has not been given any value is known as null variable, a
null variable can be created in any of the following ways.
re

1 $n=””
Sh

2 $n=’’
3 $n=
$echo n

On echoing a null variable, only a blank line appears on the screen.


CONSTANT

Constant is a fixed value. It doesn’t change during execution of the program

$a=20
$read only a

LINUX BASICS MATERIAL 60 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

When the variables are made read only, the shell does not allow us to change their values. So a

value can read but can’t change

Note: If we want the shell to forget about a variable altogether, we use the unset command.

$unset a

ies
On issuing the above command the variable and with it the value assigned to it is erased from the shell’s

memory.

Expr: expr is the command to evaluating arithmetic expressions. But expr is capable of carrying out only

og
integer arithmetic.

ol
CONTROL STATEMENTS

hn
There are four types of control instructions in shell. They are:

1. Sequence control instruction


c
Te
2. Selection or decision control instructions

3. Repetition or loop control instruction


ai

4. Case control Instruction


eS

The sequence control instruction ensures that the instructions are executed in the same order in which
they appear in the program. Decision and case control instructions allow the computer to take a decision
re

as to which instruction is to be executed next. The loop control instruction helps computer to execute a

group of statements repeatedly


Sh

Sequence control statement.

Ls –a

Pwd

clear

Write a program to read 2 numbers and display sum, difference, product and division.

LINUX BASICS MATERIAL 61 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

Echo “enter 2 numbers”

Read a b

C=`expr $a + $b`

Echo “a+b=$c”

ies
C=`expr $a - $b`

Echo “a-b=$c”

og
C=`expr $a \* $b`

ol
Echo “a*b=$a”

hn
C=`expr $a / $b`

Echo “a/b=$c”

c
Te
DECISION CONTROL STATEMENT.

If – then – fi statement
ai

Syntax
eS

If control command
re

-----------------------

----------------------
Sh

fi

The if statement of unix is concerned with the exit status of a command . The exit status indicates whether
the command was executed successfully or not. The exit status of a command is 0 if it has been executed

successfully, 1 otherwise.

Write a program to change directory

LINUX BASICS MATERIAL 62 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

Echo enter directory name

Read dname

If cd $dname

Then

ies
Echo “changed to $dname”

Pwd

og
fi

ol
if else

hn
Syntax

If condition

c
Te
Then

-------
ai

-------
eS

Else
re

-------

-------
Sh

Fi

The exit status of the control command is 0 then it executes then statements otherwise it executes else

statements.

Write a program to copy a file

Echo enters source filename and target filename


LINUX BASICS MATERIAL 63 www.shreesaitechnologies.com
040-23752633 LINUX BASICS MATERIAL

Read src trg

If cp $src $ trg

Then

Echo file copied successfully

ies
Else

Echo failed to copy the file

og
Fi

ol
Write a program to check given no is even or odd

hn
Echo enter a number

Read n

c
Te
If [ `expr $n % 2` -eq 0 ]

Then
ai

Echo $n is even number


eS

Else
re

Echo $n is odd number

Fi
Sh

The Test command

If constructs depends upon whether or not the condition results into true or not.

If constructs are generally used in conjuction with the test command.

The test command helps us to find the contents of a variable, the number of variables and the type of file

or kind of file permission. The test command returns an exit status after evaluating the condition.

Syntax

If test condition
LINUX BASICS MATERIAL 64 www.shreesaitechnologies.com
040-23752633 LINUX BASICS MATERIAL

Then

Commands

Else

Commands

ies
Fi

Write a program to compare two strings

og
Echo “enter first string:”

ol
Read str1

hn
Echo” enter second strings:”

Read str2

c
Te
If [ $str1 = $str2 ]

Then
ai

Echo “both strings are equal”


eS

Else
re

Echo “ strings are not equal”

Fi
Sh

Case control statement

Syntax

Case value in

Choice1)

---------

--------

LINUX BASICS MATERIAL 65 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

;;

Choice2)

--------

-------

ies
;;

Choice 3)

og
---------

ol
---------

hn
;;

Choice n)

c
Te
---------

---------
ai

;;
eS

*)
re

---------

---------
Sh

;;

Esac

Firstly, the expression following the case keyword is evaluated. The value that it yields is then matched, one

by one against the potential choices(choice1,choice2,choice3 in the above from ).When a match is found,
the shell executes all commands in that case up to ;; this pair of semicolons placed at the end of each
choice as necessary.

Simple program using case to print the numbers

LINUX BASICS MATERIAL 66 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

Echo “enter a number between 1 t0 4 “/c”

Read num

Case $num in

1) Echo “you entered 1”

ies
;;

2) Echo “ you entered 2”

og
;;

ol
3) Echo “ you entered 3”

;;

hn
4) Echo “ you entered 4”

;; c
Te
*) echo “ invalid number enter number between 1 to 4”
ai

;;
eS

Esac

Looping control statements


re

A loop involves repeating some portion of the program either a specified number of times of times or until
Sh

a particular condition is being satisfies there are there methods by way of which we can retreat a part of a

program. There are

1) Using a while statement


2) Using a until statement
3) Using a for statement

1) While statement
Syntax

LINUX BASICS MATERIAL 67 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

While [condition]

Do
--------------

--------------
--------------
Done

ies
The statement with in the while loop would keep on getting executed till the condition is true.

When the condition is false, the control transfers to after done statement.

og
Write a program display numbers 1 to 10

ol
hn
Echo “the number from 1 to 10 is:”

I=10;

c
Te
While [ $i –le 10 ]

Do
ai

Echo $i
eS

I=`expr $i + 1`
re

Done
Sh

The break statement

When the keyword break is encountered inside any loop, control automatically passes to the first

statement after the loop.

The continue statement

LINUX BASICS MATERIAL 68 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

When the keyword continues is encountered inside any loop, control automatically passes to the

beginning of the loop.

Write a program display file contents if file existing

X=0

ies
While test $x=0

Do

og
Echo “enter a file name: \c”

Read fname

ol
If test! –f $fname

hn
Then

Echo “$ fname is not found ….” c


Te
Continue
ai

Else break
eS

Fi

Done
re

Cat $ fname | more


Sh

The until loop

Syntax

Until [condition]

Do

-----------

--------

--------
LINUX BASICS MATERIAL 69 www.shreesaitechnologies.com
040-23752633 LINUX BASICS MATERIAL

Done

The statements within the until loop keep on getting executed till the condition is false .when the condition

is true the control transfers to after done statement.

Write a program print numbers 1 to 10

ies
I=1

Until [ $i –gt 10 ]

og
Do

Echo $i

ol
I=`expr $i + 1`

hn
Done

The true and false command c


Te
To execute the loop an infinite no of times.
ai

The for loop


eS

Syntax

For variable in value1 value2 value3 ……….value


re

Do
Sh

----------------------

---------------------

---------------------

Done

The for allows us to specify a list of values which the variable in the loop can take. The loop is then

executed for each value mentioned in the list.

Write a program to demonstrate for loop

LINUX BASICS MATERIAL 70 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

For I In 1 2 3 4 5

Do

Echo $i

Done

ies
Write a program to display all sub-directories in the current directory

For I in *

og
Do

ol
If [ -d $i ]

Then

hn
Echo $i

Fi
c
Te
Done

Shell parameters Significance


ai

$1,$2,-----,$9 Positional parameters representing command line


arguments
eS

$# No. Of arguments specified in command line


$0 No of executed commands
re

$* Complete set of positional parameters as a single


string
Sh

$@ Each quoted string treated as a separate


argument(recommended over $*)
$? Exit status of last command
$$ Pid of current shell

Positional parameters
When the arguments are passed with the command line, shell puts each word on the command line into

special variables. For this, the shell uses something called as “positional parameters”; these can be thought
of as variables defined by the shell. They are nine in number, named $1 through $9.

LINUX BASICS MATERIAL 71 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

Consider the following statement where program is any executable shell script file and the remaining are

the arguments.

On entering such command, each word is automatically stored serially in the positional parameters thus,
$0 would be assigned program, $1 would be assigned smmit $2 networks $3 is and so on till institute which

is assigned to $9

ies
Write program to copy a file using positional parameters

If cp $1 $2

og
Then

ol
Echo “file copied successfully”

hn
Else

Echo “failed to copy”

c
Te
Fi

In above command it passes a1 to $1 and a2 to $2 , then it copies a1 contents to a2.


ai

$* - contains entire string of arguments


eS

$# - contains the no for arguments specified in the command


re

FILE TEST
Sh

TEST TRUE IF
-f file file exists and is regular file
-r file file exists and is readable
-w file file exists and is writable
-x file file exists and is executable
-e file file exists
-s file file exists and has as be greater than zero bytes
-L file file exists and is symbolic link
F1 –nt f2 f1 is newer than f2
F2 –ot f2 f1 is older than f2
F1 –ef f2 f1 is linked to f2

LINUX BASICS MATERIAL 72 www.shreesaitechnologies.com


040-23752633 LINUX BASICS MATERIAL

-O file true if the file is effectively owned by you


-G file true if the file is effectively owned by your group

MISCELLANEOUS
Format options Purpose of Option Output

ies
date +%a Displays Weekday name in short (like Mon, Tue, Wed) Thu
date +%A Displays Weekday name in full short (like Monday, Tuesday) Thursday
date +%b Displays Month name in short (like Jan, Feb, Mar ) Feb

og
date +%B Displays Month name in full short (like January, February) February
date +%d Displays Day of month (e.g., 01) 07

ol
date +%D Displays Current Date; shown in MM/DD/YY 02/07/13
date +%F Displays Date; shown in YYYY-MM-DD 2013-02-07

hn
date +%H Displays hour in (00..23) format 23
date +%I Displays hour (01..12) format 11
date +%j Displays day of year (001..366) c 038
Te
date +%m Displays month (01..12) 02
date +%M Displays minute (00..59) 44
ai

date +%S Displays second (00..60) 17


date +%N Displays nanoseconds (000000000..999999999) 573587606
eS

date +%T Displays time; shown as HH:MM:SS 23:44:17


Note: Hours in 24 Format
date +%u Displays day of week (1..7); 1 is Monday 4
re

date +%U Displays week number of year, with Sunday as first day of week (00..53) 05
Sh

date +%Y Displays full year i.e. YYYY 2013

LINUX BASICS MATERIAL 73 www.shreesaitechnologies.com

You might also like