0% found this document useful (0 votes)
75 views

Introduction To Unix: Unit 2:the File System and Some File Handling Commands

The document discusses the UNIX file system and some file handling commands. It defines files and their attributes like file type, name, size, protection and timestamps. It describes different file types like ordinary files, directory files and device files. It explains commands like pwd, cd, mkdir, rmdir, ls and cat that are used to create, remove, list and view file contents. It also covers copying files using the cp command and defining absolute and relative pathnames.

Uploaded by

Loli Bhai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views

Introduction To Unix: Unit 2:the File System and Some File Handling Commands

The document discusses the UNIX file system and some file handling commands. It defines files and their attributes like file type, name, size, protection and timestamps. It describes different file types like ordinary files, directory files and device files. It explains commands like pwd, cd, mkdir, rmdir, ls and cat that are used to create, remove, list and view file contents. It also covers copying files using the cp command and defining absolute and relative pathnames.

Uploaded by

Loli Bhai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

INTRODUCTION TO UNIX

UNIT 2 :THE FILE SYSTEM AND SOME FILE HANDLING


COMMANDS
INTRODUCTION

File: collection of data

File consisting of file attributes.i.e, information related to file such as

● File type
● File name
● Physical file size
● File protection
● file time stamp
THE FILE SYSTEM
FILE TYPES
1. Ordinary files : An ordinary file is a file on the system that contains data, text, or
program instructions.

It can be divided into 2 types

1) Text File
2) Binary file
1. Directory files : UNIX directories are equivalent to folders. A directory file contains
an entry for every file and subdirectory that it houses. If you have 10 files in a
directory, there will be 10 entries in the directory. Each entry has two components.

(1) The Filename


(2) A unique identification number for the file or directory (called the inode number)

2. Device files : used to describe physical device. FAT---FILE MANAGER


Pwd COMMAND
pwd stands for Print Working Directory. It prints the path of the working directory, starting from the
root.
pwd is shell built-in command(pwd) or an actual binary(/bin/pwd).
$PWD is an environment variable which stores the path of the current directory.

● $pwd ----> /home/mint


$cd pgm
$pwd ---> /home/mint/pgm

● $pwd
/home/mint
$cd /abc/xyz
$pwd
/abc/xyz
● $pwd

/home/var/ftp

$cd /var/ftp/pub

$pwd

/var/ftp/pub
cd COMMAND
cd command in linux known as change directory command. It is used to change current working
directory.
Syntax: $ cd [directory]

● cd /: this command is used to change directory to the root directory, The root directory is the first
directory in your filesystem hierarchy.
Ex:$ cd /
● Cd ~
$pwd
● cd .. : this command is used to move to the parent directory of current directory, or the directory
one level up from the current directory. “..” represents parent directory.
Ex: $ cd ..
Mkdir command
It is used to create directory.This command can create multiple directories at
once as well as set the permissions for the directories

Syntax: mkdir [options...] [directories ...]

SUBOPTIONS
● -v or --verbose: It displays a message for every directory created.

mkdir -v [directories]
● To create directory under current directory

$mkdir mydir
● To create no.of sub directories with one mkdir

$mkdir dir1 dir2 dir3

● To create directory hierarchy

$mkdir mydir mydir/progs mydir/progs/data

● $mkdir -v mydir ←- directory created ‘mydir’


● mkdir -m a=rwx mydir ←- allocated read write and execute
permissions to directory mydir.
● We can also use a=r for read only permission.
Rmdir command
rmdir command is used remove empty directories from the filesystem in Linux. The
rmdir command removes each and every directory specified in the command line only if
these directories are empty. So if the specified directory has some directories or files in
it then this cannot be removed by rmdir command.

Syntax: $rmdir [options] directoryname


● rmdir -p: In this option each of the directory argument is treated as a pathname of
which all components will be removed, if they are already empty, starting from the
last component.

Ex: rmdir -p mydir/mydir1


Other examples
1. rmdir mydir1 mydir2 mydir3

Remove the directories mydir1, mydir2, and mydir3, if they are empty. If any of these
directories are not empty, then an error message will be printed for that directory, and
the other directories will be removed.

2. rmdir mydir/mydir1 mydir

Remove the directory mydir/mydir1 if it is empty. Then, remove directory mydir, if it is


empty after mydir/mydir1 was removed.

3. $mkdir mydir

$ls

Cd \mydir

Rmdir mydir
ABSOLUTE PATHNAME
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 / and alpha-numeric characters.
Absolute Path-name
An absolute path is defined as the specifying the location of a file or directory from
the root directory(/).
An absolute path is defined as specifying the location of a file or directory from
the root directory(/). In other words,we can say that an absolute path is a complete
path from start of actual file system from / directory.
To write an absolute path-name:
● Start at the root directory ( / ) and work down.
● Write a slash ( / ) after every directory name (last one is optional)
For Example :
$cat abc.sql

will work only if the fie “abc.sql” exists in your current directory. However, if this file is
not present in your working directory and is present somewhere else say in /home/kt ,
then this command will work only if you will use it like shown below:
cat /home/kt/abc.sql
In the above example, if the first character of a pathname is /, the file’s location must be
determined with respect to root. When you have more than one / in a pathname, for
each such /, you have to descend one level in the file system like in the above kt is one
level below home, and thus two levels below root.
RELATIVE PATH
● Relative path is defined as the path
related to the present working
directly(pwd). It starts at your current
directory and never starts with a / .
● To be more specific let’s take a look on
the below figure in which if we are
looking for photos then absolute path
for it will be provided as
/home/jono/photos but assuming that
we are already present in jono
directory then the relative path for
the same can be written as simple
photos.
UNIX offers a shortcut in the relative pathname– that uses either the current or parent
directory as reference and specifies the path relative to it.

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

..(two dots) - this represents the parent directory.


EX: $pwd

/home/kt/abc

$cd ..

$pwd
As shown in the current example, if we are currently in directory /home/kt/abc and now
you can use .. as an argument to cd to move to the parent directory /home/kt
ls COMMAND
ls is a Linux shell command that lists directory contents of files and directories

Syntax: $ls [option].....[files]

Options:

● Display One File Per Line Using ls -1


● Display All Information About Files/Directories Using ls -l
$ ls -l : To show long listing information about the file/directory.
Field Explanation
● – normal file
● d : directory
● s : socket file
● l : link file
● Field 1 – File Permision
● ls -F : Instead of doing the ‘ls -l’ and then the checking for the first character to
determine the type of file. You can use -F which classifies the file with different special
character for different kind of files.
/ – directory.
nothing – normal file.
@ – link file.
* – Executable file

● Ls -l /etc:lists files/directories of etc directory from current working directory


● Display File Inode Number Using ls -i
Sometimes you may want to know the inode number of a file for internal maintenance.
Use -i option as shown below to display inode number. Using inode number you can
remove files that has special characters in it’s name.
Ex: $ ls -i
● Display Hidden Files Using ls -a (or) ls -A
$ ls -a : To show all the hidden files in the directory, use ‘-a option’. Hidden files in Unix
starts with ‘.’ in its file name.It will show all the files including the ‘.’ (current directory)
and ‘..’ (parent directory).
● Open Last Edited File Using ls -t
ls -t : It sorts the file by modification time, showing the last edited file
first. head -1 picks up this first file.To open the last edited file in the
current directory use the combination of ls and head commands
● Display File Size in Human Readable Format Using ls -lh
● Display Files Recursively Using ls -R
● Sort files by their sizes ls - S
● Ls -x :list entries by lines
HANDLING ORDINARY FILES
● CREATING AND DISPLAYING FILES
● Cat COmmand
It reads data from the file and gives their content as output. It helps us to create,
view, concatenate files.

i) To view a single file : $cat filename

Ex:$cat a.txt

ii) To view multiple files : $cat file1 file2

Ex: $cat a.txt b.c


iii) To view contents of a file preceding with line numbers.
Command: $cat -n filename
Ex: $cat -n a.txt
iv) To Create a file
Command: $ cat > filename
Ex: $cat > s.txt
v)To suppress multiple empty lines in output
Command :$ cat -s fileneme
Ex: $ cat -s a.txt
● Cat command can append the contents of one file to the end of another file.
Command: $cat file1 >> file2
Above command will append the contents of one file to the end of
another file

● Copy the contents of one file to another file.


Command: $cat [filename-whose-contents-is-to-be-copied] >
[destination-filename]
By using above command the content will be copied in destination file

● Cat command can display content in reverse order using tac command.
Command: $tac filename
COPYING A FILE
● cp stands for copy. This command is used to copy files or group of files or
directory.
● It creates an exact image of a file on a disk with different file name.
● cp command require at least two filenames in its arguments.
● If the command contains two file names, then it copy the contents of 1st file to the
2nd file. If the 2nd file doesn’t exist, then first it creates one and content is copied
to it. But if it existed then it is simply overwritten without any warning.

Syntax: cp Src_file Dest_file


Ex: $ ls
a.txt
$ cp a.txt b.txt
$ ls
a.txt b.txt
● If the command has one or more arguments, specifying file names and following
those arguments, an argument specifying directory name then this command
copies each source file to the destination directory with the same name, created if
not existed but if already existed then it will be overwritten
Syntax: cp Src_file1 Src_file2 Src_file3 Dest_directory
$ ls

a.txt b.txt new

Initially new is empty

$ ls new

$ cp a.txt b.txt new

$ ls new

a.txt b.txt
Two directory names : If the command contains two directory names, cp copies all
files of the source directory to the destination directory, creating any files or directories
needed. This mode of operation requires an additional option, typically R, to indicate
the recursive copying of directories.

Syntax: cp -R Src_directory Dest_directory


In the above command, cp behavior depend upon whether Dest_directory is exist or
not. If the Dest_directory doesn’t exist, cp creates it and copies content of Src_directory
recursively as it is. But if Dest_directory exists then copy of Src_directory becomes
sub-directory under Dest_directory.
OPTIONS
● -i(interactive): i stands for Interactive copying. With this option system first warns the
user before overwriting the destination file. cp prompts for a response, if you press y
then it overwrites the file and with any other option leave it uncopied.
$ cp -i a.txt b.txt

cp: overwrite 'b.txt'? y

$ cat b.txt

hello
● -b(backup): With this option cp command creates the backup of the
destination file in the same folder with the different name and in different
format.
$ ls
a.txt b.txt
$ cp -b a.txt b.txt
$ ls
a.txt b.txt b.txt~
-f(force): If the system is unable to open destination file for writing operation
because the user doesn’t have writing permission for this file then by using -f
option with cp command, destination file is deleted first and then copying of
content is done from source to destination file.
$ ls -l b.txt
-r-xr-xr-x+ 1 User User 3 Nov 24 08:45 b.txt
User, group and others doesn't have writing permission.
Without -f option, command not executed
$ cp a.txt b.txt
cp: cannot create regular file 'b.txt': Permission denied
With -f option, command executed successfully
$ cp -f a.txt b.txt
Copying using * wildcard: The star wildcard represents anything i.e. all files and
directories.

Ex: Initially Folder1 is empty

$ ls

a.txt b.txt c.txt d.txt e.txt Folder1

$ cp *.txt Folder1

$ ls Folder1

a.txt b.txt c.txt d.txt e.txt


User group others
Rw- rw- r--
DELETING FILES
● rm stands for remove here. rm command is used to remove objects such as
files, directories, symbolic links and so on from the file system like UNIX.

● Once we delete the files using rm command then it is not able to recover the
contents of files and directories.
Syntax: rm [OPTION]... FILE…
● Removing one file at a time : $rm filename
$ rm a.txt
● Removing more than one file at a time:$rm file1 file2
$ rm b.txt c.txt
● -i (Interactive Deletion): Like in cp, the -i option makes
the command ask the user for confirmation before
removing each file, you have to press y for confirm
deletion, any other key leaves the file un-deleted.
$ rm -i d.txt
rm: remove regular empty file 'd.txt'? Y
$ ls
e.txt
● -f (Force Deletion): rm prompts for confirmation removal if a file is write protected.
The -f option overrides this minor protection and removes the file forcefully.
$ ls -l

total 0

-r--r--r--+ 1 User User 0 Jan 2 22:56 e.txt

$ rm e.txt

rm: remove write-protected regular empty file 'e.txt'? n

$ ls

e.txt

$ rm -f e.txt

$ ls
-r (Recursive Deletion): With -r(or -R) option rm command performs a tree-walk and will
delete all the files and sub-directories recursively of the parent directory. At each stage it
deletes everything it finds.

$ ls

$ cd A

$ ls

B C

$ ls B

a.txt b.txt

$ ls C

c.txt d.txt
Now, deletion from A directory(as parent directory) will be done as:
$ rm *

rm: cannot remove 'B': Is a directory

rm: cannot remove 'C': Is a directory

$ rm -r *

$ ls

Every directory and file inside A directory is deleted.


mv COMMAND:RENAMING FILES
● mv stands for move. mv is used to move one or more files or directories from one
place to another in a file system like UNIX. It has two distinct functions:

(i) It renames a file or folder.

(ii) It moves a group of files to a different directory.

● No additional space is consumed on a disk during renaming. This command


normally works silently means no prompt for confirmation.
● Syntax: mv [Option] source destination
EX: mv a.txt aa.txt----> to rename file a.txt to aa.txt
● If the destination file doesn’t exist, it will be created.
● Mv can also be used to rename a directory
Ex: mv dir1 dir2
Group of files can be moved to a directory

$mv file1 file2 dir1

OPTIONS:

● -i option
● -f option
● -n option
● -b option
more COMMAND IN UNIX
more command is used to view the text files in the command prompt, displaying one screen at a
time in case the file is large (For example log files). The more command also allows the user do
scroll up and down through the page.

Ex: more chap01 ---> To view the content of file chap01

From above example ,the contents of chap01 on the screen will be visible one page at a

time.At the bottom of the screen we see the filename and the percentage of the file that has
been viewed. ‘q’ is one of the internal command of more Pager from which more pager can
be exited
● NAVIGATION:
1. More uses space bar to scroll forward a page.
2. To move forward 1 page use space bar or ‘f’
3. To move one page back ude ‘b’
● THE REPEAT FEATURES:

By using the repeat factor as a command prefix simply repeat the command that
many times.

Ex: 10f---> to scroll 10 pages forward,then to continue the forwarding of again 10


pages,use ‘.’

‘.’ is used to repeat last command


wc COMMAND IN UNIX
wc stands for word count. As the name implies, it is mainly used for counting purpose.
● It is used to find out number of lines, word count, byte and characters count in the files
specified in the file arguments.
● By default it displays four-columnar output.
● First column shows number of lines present in a file specified, second column shows
number of words present in the file, third column shows number of characters present in
file and fourth column itself is the file name which are given as argument.

Syntax:wc [OPTION]... [FILE]...


Ex:
Passing only one file name in the argument.

$ wc state.txt

5 7 63 state.txt

Passing more than one file name in the argument.

$ wc state.txt capital.txt

5 7 63 state.txt

5 5 45 capital.txt

10 12 108 total
When more than file name is specified in argument then command will display four-columnar
output for all individual files plus one extra row displaying total number of lines, words and
characters of all the files specified in argument, followed by keyword total.
OPTIONS
● -l: This option prints the number of lines present in a file. With this option wc command displays
two-columnar output, 1st column shows number of lines present in a file and 2nd itself represent
the file name.
EX:
With one file name
$ wc -l state.txt
5 state.txt
With more than one file name
$ wc -l state.txt capital.txt
5 state.txt
5 capital.txt
10 total
● -w: This option prints the number of words present in a file. With this option wc command
displays two-columnar output, 1st column shows number of words present in a file and 2nd is
the file name.
EX:
With one file name

$ wc -w state.txt

7 state.txt

With more than one file name

$ wc -w state.txt capital.txt

7 state.txt

5 capital.txt

12 total
● -c: This option displays count of bytes present in a file. With this option it display two-columnar
output, 1st column shows number of bytes present in a file and 2nd is the file name.
EX:
With one file name

$ wc -c state.txt

63 state.txt

With more than one file name

$ wc -c state.txt capital.txt

63 state.txt

45 capital.txt

108 total
od COMMAND
● od command in Linux is used to convert the content of input in different formats with
octal format as the default format.
● This command is especially useful when debugging Linux scripts for unwanted changes
or characters.
● If more than one file is specified, od command concatenates them in the listed order to
form the input.
● It can display output in a variety of other formats, including hexadecimal, decimal, and
ASCII.

Syntax :
od [OPTION]... [FILE]...
OPTIONS

1. -b Option :It displays the contents of input in octal format.

SYNTAX: $ od -b input.txt

The first column in the output of od represents the byte offset in file.

2.-c Option :It displays the contents of input in character format.

SYNTAX :$ od -c input.txt
cmp COMMAND
cmp command in Linux/UNIX is used to compare the two files byte by byte and helps you to find out
whether the two files are identical or not.

Syntax:

cmp [OPTION]... FILE1 FILE2

EX:

$cat list1.txt

Hello

$cat list2.txt

Hi

$cmp list1 list2


comm COMMAND
comm compare two sorted files line by line and write to standard output; the lines that are
common and the lines that are unique.
● Syntax: comm [options] file1 file2

EX:
// displaying contents of // displaying contents
file1 // of file2 //
$cat file1.txt $cat file2.txt
Apaar
Apaar
Hemant
Ayush Rajput
Lucky
Deepak
Pranjal Thakral
Hemant
$comm file1.txt file2.txt
Apaar
Ayush Rajput
Deepak
Hemant
Lucky
Pranjal Thakral
diff COMMAND
diff stands for difference. This command is used to display the differences in the files by
comparing the files line by line.

cmp and comm, it tells us which lines in one file have is to be changed to make the two files
identical.

The important thing to remember is that diff uses certain special symbols and instructions
that are required to make two files identical. It tells you the instructions on how to change the
first file to make it match the second file.

Special symbols are:


a : add

c : change

d : delete
Syntax : diff [options] File1 File2
Ex: $cat > a.txt
In the given output of
diff command
Chapter1
1,2c1 can be described
as,lines from 1 to 2 from
Chapter2 first file need to be
changed to be changed
$cat > b.txt to match 1st line in file
2.
Chapters

$diff a.txt b.txt

1,2c1

< chapter1 …... Lines preceded by a < are lines from the first file.

< chapter2

> chapters……. Lines preceded by > are lines from the second file.
Spell and ispell COMMANDS
● The spell command is a spell-checking program which scans a text file for
misspelled words, and prints each misspelled word on its own line.
● spell is a very minimalistic spell-checking program, based on the original UNIX spell
checker. It reads the contents of file FILE, word for word, checking them against its
dictionary. If a word does not correspond with any of spell's dictionary words, the
word is printed.

Syntax : spell [OPTIONS] FILE …


EX: $spell -on words.txt words2.txt

Checks the spelling of files words.txt and words2.txt, printing the file name (-o)
and the line number (-n) of each misspelled word.
ispell
ispell command is used as a spell checker in Linux. Generally, it will scan the given files or
anything from standard input then it check for misspellings. Finally it allows the user to correct the
words interactively.
Syntax:ispell check [options] filename
Options:
● -a : To check individual words.
● -c : Check a file for specific error.

Example 1: Check a file for spelling errors


aspell -c sample.txt
Dos2unix and unix2dos :
Sometimes, you will need to move files between windows and unix systems. Window files use the same
format as Dos.

● dos2unix command : converts a DOS text file to UNIX format.


● Unix2dos command : converts a Unix text file to DOS format
Example

Task : Create a file in DOS or in notepad with following


contents
hello everybody
welcome to unix
unix is easy

now copy this file in unix /home/abc directory


$od –bc myfile.txt
convert DOS file to UNIX format by using dos2unix command
$dos2unix myfile.txt

$od –bc myfile.txt


We can also convert UNIX file to DOS format by using unix2dos
command
$unix2dos myfile.txt

$od –bc myfile.txt


Gzip and gunzip COMMANDS IN UNIX
● On Unix-like operating systems, the gzip command creates, lists,
modifies, and extracts data from GZIP archives.
● Gzip reduces the size of the named files using Lempel-Ziv coding (LZ77).
Whenever possible, each file is replaced by one with the extension .gz, while
keeping the same ownership modes, access, and modification times.
● gzip only attempt to compress regular files.

SYNTAX: $gzip filename

EX: gzip abc.txt

After compressing it will become abc.txt.gz


gunzip COMMAND
● Compressed files can be restored to their original form using gzip -d or gunzip .
● Gunzip takes more than one file names as arguments

SYNTAX:$gunzip filename

EX:$gunzip abc.txt.gz
Zip and Unzip COMMAND
zip is used to compress the files to reduce file size and also used as file package utility.

The zip program puts one or more compressed files into a single zip archive, along with
information about the files (name, path, date, time of last modification, protection, and check
information to verify file integrity).

Syntax :
zip [options] zipfile files_list
$zip myfile.zip filename.txt
Unzip will list, test, or extract files from a ZIP archive, commonly found on Unix
systems. The default behavior (with no options) is to extract into the current
directory (and sub-directories below it) all files from the specified ZIP archive.
Syntax :

$unzip myfile.zip
-d Option: Removes the file from the zip archive. After creating a zip file, you
can remove a file from the archive using the -d option.
Syntax :
$zip –d filename.zip file.txt
Command :
$zip –d myfile.zip hello7.c OR $unzip myfile.zip hello7.c
After removing hello7.c from myfile.zip file, the
Suppose we have following files in my current
files can be restored with unzip command
directory are listed below:
Command:
hello1.c
$unzip myfile.zip
hello2.c $ls command

hello3.c Output :
hello1.c
hello4.c
hello2.c
hello5.c hello3.c

hello6.c hello4.c
hello5.c
hello7.c
hello6.c
Hello8.c hello8.c
The hello7.c file is removed from
$zip –d myfile.zip hello7.c
zip file

You might also like