Module 2
Handling Ordinary Files:
FILE RELATED COMMANDS – CAT, MV, RM, CP, WC AND OD COMMANDS
ls : listing directory contents:
To obtain a list of all filenames in the current directory.
Numerals first Uppercase next Lowercase Then
$ls Output:08_packets.html calendar
dept.lst emp.lst helpdir uskdsk06
Cat command : Displaying and creating files
cat is one of the most well known commands of UNIX system. Cat is useful for creating a file
Its mainly used to display the contents of a small file on the terminal.
Using cat to create a file:
Enter the command cat, followed by >(right chevron) character and the filename. Example: take
a filename named foo
$ cat > foo
> Symbol following command means that the output goes to filename following it. [ctrl+d] /*
to terminate or to signify end of the input.
$
Using cat to display a file
Enter the cat command followed by filename
$ cat foo
Symbol following command means that the output goes to filename following it.
Cat options (-v and -n)
Displaying Non printing characters(-v)
cat is normally used for displaying text files only. If you have non-printing ASCII characters in
your input , you can see cat with -v option to display these characters
Numbering lines(-n)
The -n option numbers lines.
cat with more than one filename as arguments:
cat filename1 filename2 .... cat chap01 chap02
The contents of second file are displayed immediately after the first file without any header
information.
mv: Renaming Files.
The mv command renames or moves files. It has two distinct functions:
It renames a file or directory
it moves a group of files to a different directory
To rename a file chap01 to man01
$ mv chap01 man01
mv replace the filename in the existing directory entry with the new name. No additional space
is consumed on disk during renaming.
To rename a directory:
$ mv pts perdir
pts directory is renamed as perdir
To move group of files to a directory mv chap01 chap02 chap03 progs
to move three files chap01, chap02, chap03 to directory named progs.
rm : deleting files
The rm command deletes one or more files.
Ex 1: The following command deletes three files chap01, chap02, chap03.
$ rm chap01 chap02 chap03
Ex 2: to delete files named chap01 and chap02 under progs directory
$ rm progs/chap01 progs/chap02
Ex 3: to remove all file
$ rm*
rm options:
Interactive deletion (-i): the –i optin makes the command ask the user for confirmation
before removing each file.
$rm -i chap01 chap02 chap03 rm: remove chap01(yes/no)?y rm: remove chap01(yes/no)?y
rm: remove chap01(yes/no)?y
Recursive deletion(-r or -R) deletes all subdirectories and files recursively. Rm wont
normally remove directories but when used with -r or -R option it will.
$ rm -r *
Forcing removal: rm prompts for removal, if a file is write protected. The -f option overrides
this minor protection and forces removal.
$ rm -rf * /*(deletes everything in the current directory and below)
cp: copying a file
cp command copies a file or a group of files.it creates an exact image of the file on the disk with
the different name.
The syntax requires atleast two filenames to be specified in the command line.
When both are ordinary files, the first is copied to second file. cp source file destination file
cp chap01 unit1
if destination file i.e unit1 does not exist, first it will be created before copying.if not it will be
simply overwritten without any warning.
Copying a file to another directory
ex: assume there is a file named chap01 and it has to be copied to progs directory
cp chap01 progs
output: chap01 is now copied to directory named progs with the same name chap01.
Copying a file to another directory with different name
ex: assume there is a file named chap01 and it has to be copied to progs directory with
chap01 file renamed as unit1
cp chap01 progs/unit1
output: chap01 is now copied to directory named progs with the same name unit1
Copy more than one file with a single command.
cp chap01 chap02 chap03 progs
chap01, chap02, chap03 files are copied to directory named progs.
Copy all files beginning with chap
cp chap* progs cp options:
Interactive copying (-i): the -i option warns the user before overwriting the destination file.
Ex: $ cp -i chap01 unit1
cp: overwrite unit1(yes/no)? y
A y at this prompt will overwrite the file.
Copying directory structure(-R) : the -R command behaves recursively to copy an entire
directory structure say progs to newprogs.
Ex say progs directory contains three files kernel, bash, korn. To copy all three files under
progs to newprogs directory
$ cp -R progs newprogs
wc command: Counting Lines, Words, Characters
wc command takes one or more filenames as arguments and displays four columnar output. First
we will create a file named infile
$ cat > infile
I am the wc command
I count characters,words and lines [ctrl+D]
$wc infile
2 10 55 infile
wc counts lines in first column ,words in second column,characters in third column and
filename in fourth column.
A line is any group of characters not containing a newline
A word is group of characters not containing a space tab or newline.
A character is the smallest unit of information and includes a space, tab and newline wc options:
$ wc -l infile 2 $
$wc -c infile 55
When two filenames are passed as wc argument
First line : number of lines, words and characters of chap01 Second line: number of lines, words
and characters of chap02 Third line: Total number of lines, words and characters of both.
od Command: Displaying Data In Octal.
$ cat odfile
White space includes a
The ^G character rings a bell
$ od -b odfile
The -b option displays the octal values for each character.
000000 127 150 151 164 145 040 163 160 141 143 145 040 151 156 143 154
000000 165 144 145 163 040 141 040 011 012 124 150 145 040 007 040 143
Each line displays 16 bytes of data in octal , preceded by the offset in the file of the first byte in
the line.
$od -bc odfile
The -b and -c option combined. Each line is now replaced with two.
The octal values are shown in first line and printable characters and escape sequences are
shown in second line
000000 127 150 151 164 145 040 163 160 141 143 145 040 151
W h i t e s p a c e i 156 143 154
n c l
000000 165 144 145 163 040 141 040 011 012 124 150 145 040
u d e s a \t \n T h e 007 040 143
007 c
The octal equivalent of characters are displayed ex for W- 127, i-151, \t (tab)-011,
\n(newline)-012 ^G(Bell character)- 007.
more Command in Ubuntu
The more command in Ubuntu is used to view the contents of a file one page at a time in the
terminal. It is useful for reading long text files without opening an editor.
Basic Syntax
$ more [options] filename
• Common Uses
View a file page by page
$more filename.txt
o Press Spacebar to go to the next page.
o Press Enter to scroll line by line.
o Press q to quit.
View long command output
$ ls -l | more
• This paginates long directory listings.
Display file with line numbers
$more -n 5 filename.txt
• This shows only 5 lines at a time.
Start from a specific line
$ more +10 filename.txt
• This starts displaying from line 10.
Search inside a file
• Type /word and press Enter to search for "word" in the file.
• Press n to go to the next occurrence.
• Press N to go to the previous occurrence
File Command in Ubuntu
The file command in Ubuntu is used to determine the type of a file. It analyzes the file's
content, not just the extension, making it useful for identifying different file formats.
Basic Syntax
file [options] filename
Common Uses
Check the type of a file
$ file example.txt
Example output:
example.txt: ASCII text
Check multiple files
$ file file1.txt file2.jpg file3.bin
Example output:
file1.txt: ASCII text
file2.jpg: JPEG image data
file3.bin: data
Check all files in a directory
$file *
Display MIME type
$ file --mime-type example.png
Output:
example.png: image/png
Display more detailed information
$ file -i example.txt
Output:
example.txt: text/plain; charset=us-ascii
Identify file types of symbolic links
$ file -L symlink_name
Why Use file Instead of Relying on Extensions?
• Some files may have wrong extensions but contain different data.
• The file command examines the actual contents to determine the correct file type.
For more details, check the manual:
man file
File Output
document.txt ASCII text
photo.jpg JPEG image data
script.sh Bourne shell script
archive.tar.gz gzip compressed data
binary.exe PE32 executable
Cmp Command
• The cmp (compare) command in Ubuntu is used to compare two files byte by byte. It
is mainly used to check if two files are identical or different.
• Basic Syntax
• cmp [options] file1 file2
Common Uses
Check if two files are identical
$ cmp file1.txt file2.txt
If files are identical, there is no output.
If different, it shows the first differing byte and location.
Example output:
file1.txt file2.txt differ: byte 10, line 2
Show all differences
$cmp -l file1.txt file2.txt
This displays differing byte positions and values.
Example output:
10 101 115
15 110 120
(The numbers represent byte position, first file byte value, second file byte value.)
Compare and stop after the first difference
$cmp -s file1.txt file2.txt
No output means the files are the same.
A different exit status (1) indicates a difference.
Compare only a specific number of bytes
$cmp -n 100 file1.txt file2.txt
This compares only the first 100 bytes.
Skip initial bytes in comparison
$cmp -i 10 file1.txt file2.txt
This skips the first 10 bytes before comparing.
comm Command in Ubuntu
The comm command in Ubuntu is used to compare two sorted files line by line and display
the differences and similarities. It outputs three columns:
1. Lines unique to the first file
2. Lines unique to the second file
3. Lines common to both files
Basic Syntax
comm [options] file1 file2
Note: Both file1 and file2 must be sorted before using comm. You can sort them using:
sort file1.txt -o file1.txt
sort file2.txt -o file2.txt
Example Usage
1. Compare Two Sorted Files
comm file1.txt file2.txt
Example Output:
apple # Common in both files
banana # Only in file1.txt
orange # Only in file2.txt
1st column → Unique to file1.txt
2nd column → Unique to file2.txt
3rd column → Common to both
Suppress Specific Columns
Example: Show Only Common Lines
comm -12 file1.txt file2.txt
(Suppresses columns 1 and 2, showing only common lines.)
Example: Show Only Differences
comm -3 file1.txt file2.txt
(Suppresses the common column, showing only unique lines.)
Compare Unsorted Files
If your files are not sorted, use:
comm <(sort file1.txt) <(sort file2.txt)
This sorts the files on-the-fly before comparing them.
diff Command in Ubuntu
The diff command in Ubuntu is used to compare two files line by line and highlight the
differences. It is mainly used for text files but can also be used for directories.
Basic Syntax
diff [options] file1 file2
Example Usage
1. Basic File Comparison
diff file1.txt file2.txt
Example Output:
1c1
< Hello, world!
---
> Hello, Ubuntu!
< means the line is in file1.txt but not in file2.txt.
> means the line is in file2.txt but not in file1.txt.
Show Differences Side by Side
diff -y file1.txt file2.txt
This displays both files side by side, making it easier to compare.
3. Ignore Case Differences
diff -i file1.txt file2.txt
This makes the comparison case-insensitive.
4. Ignore White Spaces
diff -w file1.txt file2.txt
This ignores spaces, tabs, and blank lines.
5. Compare Two Directories
diff -r dir1 dir2
This recursively compares all files in dir1 and dir2.
6. Show Only Different Lines
diff --brief file1.txt file2.txt
Output Example:
Files file1.txt and file2.txt differ
This is useful for quickly checking if files are different.
Common Actions:
1. <NUM>d<NUM> → A line is deleted from f1
o Example:
o 3d2
o < This line was in f1 but not in f2
▪ Meaning: Line 3 in f1 is missing from f2, so it was deleted.
2. <NUM>a<NUM> → A line is added in f2
o Example:
o 4a5
o > This line is new in f2
▪ Meaning: A new line was added to f2 after line 4.
3. <NUM>c<NUM> → A line was changed (modified)
o Example:
o 5c5
o < This line was in f1
o ---
o > This line is modified in f2
▪ Meaning: Line 5 in f1 was changed in f2.
Example Files:
f1: f2:
apple apple
banana blueberry
cherry
cherry date
date fig
Running diff f1 f2:
2c2
< banana
---
> blueberry
5a6
> fig
Interpreting Output:
1. 2c2 → Line 2 (banana) in f1 was changed to blueberry in f2.
2. 5a6 → fig was added in f2 at line 6.
dos2unix and unix2dos Commands in Ubuntu
The dos2unix and unix2dos commands are used to convert text file formats between
Windows (DOS) and Unix/Linux systems by modifying line endings.
1. Understanding Line Endings
Different operating systems use different end-of-line (EOL) characters:
Windows (DOS format): CRLF (\r\n)
Unix/Linux: LF (\n)
When moving files between Windows and Linux, you might see issues like:
Extra ^M characters in text files (cat -A filename.txt can reveal them).
Scripts showing errors due to incorrect line endings.
Converting Windows to Unix (dos2unix)
Syntax:
dos2unix filename.txt
This removes the CR (\r) characters, converting the file to Unix format.
Example:
dos2unix windows-file.txt
To overwrite the file:
dos2unix -o filename.txt
Convert multiple files:
dos2unix file1.txt file2.txt file3.txt
Converting Unix to Windows (unix2dos)
Syntax:
unix2dos filename.txt
This adds CR (\r) before LF (\n), converting the file to Windows format.
Example:
unix2dos unix-file.txt
To overwrite the file:
unix2dos -o filename.txt
Convert multiple files:
unix2dos file1.txt file2.txt file3.txt
. Checking File Format Before Conversion
Use file command to check if a file has DOS line endings:
file filename.txt
Example Output:
filename.txt: ASCII text, with CRLF line terminators
(If CRLF appears, it's in Windows format.)
Compressing and archiving files
Compress a file using gzip:
$ gzip filename
This compresses filename and creates filename.gz.
The original filename is removed after compression.
Check compression details:
$ gzip -l filename.gz
Displays the original and compressed file sizes along with the compression ratio.
Example output:
compressed uncompressed ratio uncompressed_name
400 1500 73.3% filename
This means filename was reduced from 1500 bytes to 400 bytes (compressed by
73.3%).
Decompress a compressed file (.gz file) using gzip -d:
$ gzip -d filename.gz
Restores the original filename.
Decompress using gunzip:
$ gunzip filename.gz
This does the same as gzip -d filename.gz, restoring filename.
Compress all files in a directory recursively:
$ gzip -r dirname
Compresses all files inside dirname and its subdirectories.
Definition of tar Command
The tar (Tape Archive) command in Unix/Linux is used to create, manage, and extract archive
files. It groups multiple files and directories into a single file, making it easier to store or transfer
large sets of files. The archived file is commonly referred to as a tarball and usually has a .tar
extension.
Explanation of tar Command and Its Options
1. Creating a Tar Archive (-c for create)
o The tar -cvf command is used to create an archive.
o Syntax:
o tar -cvf archive.tar file1 file2 directory/
o Explanation:
▪ -c → Creates a new archive.
▪ -v → Verbose mode (shows the progress of archiving).
▪ -f → Specifies the archive file name.
Example:
tar -cvf mybackup.tar myfile1.txt myfile2.txt
This creates mybackup.tar containing myfile1.txt and myfile2.txt.
2. Extracting a Tar Archive (-x for extract)
o The tar -xvf command extracts files from an archive.
o Syntax:
o tar -xvf archive.tar
o Explanation:
▪ -x → Extracts files from the archive.
▪ -v → Shows the progress of extraction.
▪ -f → Specifies the archive file name.
Example:
tar -xvf mybackup.tar
This extracts all files from mybackup.tar.
3. Viewing the Contents of a Tar Archive (-t for list)
o The tar -tvf command lists the files stored inside an archive without extracting
them.
o Syntax:
o tar -tvf archive.tar
o Explanation:
▪ -t → Displays the contents of the archive.
▪ -v → Shows detailed output.
▪ -f → Specifies the archive file name.
Example:
tar -tvf mybackup.tar
This will list the names of files stored in mybackup.tar.
zip and unzip Commands
1. Creating a Zip Archive (zip Command)
• The zip command is used to compress files into a .zip archive.
• Syntax:
• zip archive_name.zip file1 file2 directory/
• Explanation:
o zip → The command to create a zip file.
o archive_name.zip → The name of the compressed archive.
o file1, file2, directory/ → The files and directories to be compressed.
• Example:
• zip myarchive.zip file1.txt file2.txt
This creates a compressed archive myarchive.zip containing file1.txt and file2.txt.
2. Extracting a Zip Archive (unzip Command)
• The unzip command is used to extract files from a .zip archive.
• Syntax:
• unzip archive_name.zip
• Explanation:
o unzip → The command to extract the files.
o archive_name.zip → The zip file to be extracted.
• Example:
• unzip myarchive.zip
This extracts all files from myarchive.zip to the current directory.
3. Viewing the Contents of a Zip Archive (unzip -v Command)
• The -v (verbose) option displays detailed information about the files inside a zip archive.
• Syntax:
• unzip -v archive_name.zip
• Explanation:
o -v → Shows the list of files inside the archive along with their sizes, compression
ratios, and other details.
• Example:
• unzip -v myarchive.zip
This displays the contents of myarchive.zip without extracting them.
File attributes and permission
BASIC FILE ATTRIBUTES
1. ls –l: LISTING FILE ATTRIBUTES
ls command is used to obtain a list of all filenames in the current directory. The output in UNIX
lingo is often referred to as the listing. Sometimes we combine this option with other options for
displaying other attributes, or ordering the list in a different sequence. ls look up the file’s inode to
fetch its attributes. It lists seven attributes of all files in the current directory and they are:
1.1 File type and Permissions
1.2 Links
1.3 Ownership
1.4 Group ownership
1.5 File size
1.6 Last Modification date and time
1.7 File name
1.1 The file type and its permissions: The first column shows the type and permissions
associated with each file.The first character in this column is mostly a – which indicates that the
file is an ordinary one. In unix, file system has three types of permissions- read, write and execute.
1.2 Links: The second column indicates the number of links associated with the file. This is
actually the number of filenames maintained by the system of that file.
1.3 Ownership: The third column shows the owner of files. The owner has full authority to
tamper with files content and permissions. Similarly, you can create, modify or remove files in a
directory if you are the owner of the directory.
1.4 Group ownership: The fourth column represents the group owner of the file. When opening a
user account, the system admin also assigns the user to some group. The concept of a group of
users also owning a file has acquired importance today as group members often need to work on
the same file.
1.5 File size: The fifth column shows the size of the file in bytes. The important thing to
remember here is that it only a character count of the file and not a measure of the disk space that
it occupies.
1.6 Last modification time: The sixth, seventh and eighth columns indicate the last modification
time of the file, which is stored to the nearest second. A file is said to be modified only if its
content have changed in any way.If the file is less than a year old since its last modification time,
the year won’t be displayed.
1.7 Filename: The last column displays the filename arranged in ASCII collating sequence.
For example, $ ls –l
total 72
-rw-r--r-- 1 kumar metal 19514 may 10 13:45 chap01
-rw-r--r-- 1 kumar metal 4174 may 10 15:01 chap02
-rw-rw-rw- 1 kumar metal 84 feb 12 12:30 dept.lst
-rw-r--r-- 1 kumar metal 9156 mar 12 1999 genie.sh
drwxr-xr-x 2 kumar metal 512 may 09 10:31 helpdir
drwxr-xr-x 2 kumar metal 512 may 09 09:57 progs
2. LISTING DIRECTORY ATTRIBUTES (-d option)
ls -d will not list all subdirectories in the current directory
For example,
$ls –ld helpdir progs
drwxr-xr-x 2 kumar metal 512 may 9 10:31 helpdir
drwxr-xr-x 2 kumar metal 512 may 9 09:57 progs
Directories are easily identified in the listing by the first character of the first column,
which here shows a d.
To see the attributes of a directory rather than the files contained in it, use ls –ld with the
direc- tory name.
3. FILE OWNERSHIP
When you create a file, you become its owner and it shows up in the third column of the
files listing.
Group name is seen in the fourth column; your group is the group owner of the file.
Every owner is attached to a group owner. Several users may belong to a single group, but
the privileges of the group are set by the owner of the file and not by the group members.
When the system administrator creates a user account, he has to assign these parameters to
the user:
The user-id (UID) – both its name and numeric
representation The group-id (GID) – both its name and
numeric representation
4. FILE PERMISSIONS
UNIX has a simple and well defined system of assigning permissions to files.
Lets issue the ls –l command once again to view the permissions of a few lines .
$ls -l chap02 dept.lst dateval.sh
-rwxr-xr-- 1 kumar metal 25000 May 10 19:21 chap02
-rwxr-xr-x 1 kumar metal 890 Jan 10 23:17 dept.lst
-rw-rw-rw- 1 kumar metal 84 Feb 1812:20 dateval.sh
Consider the first column.
-rwx r-x r—
Each group here represents the category and contain three slots representing the read, write and
execute permissions of the file.
r indicates the read permission; w indicates write permission; x indicates execute permission
- (hyphen) indicates the absence of the corresponding permission.
In the above example, the file permissions of chap02 file is
- rwx r-x r - - File owner/user group others
First group(rwx) has all the three permissions.
The file is readable, writable and executable by the owner of the file, kumar.
The third column shows the owner of the file.
The first permissions group applies to kumar.
You have to login with the name kumar for the privileges to apply to you.
Second group(r-x):
has a hyphen in the middle slot, which indicates the absence of write permissions by the group
owner of the file.
The group owner is metal and all users belonging to group metal has only read and execute
per- missions.
Third group(r--):
has the write and execute bits absent.
This set is applicable to others i,e those who are neither the owner nor group.
This category is referred to as the world.
5. CHANGING FILE PERMISSIONS- chmod command.
A file or a directory is created with a default set of permissions, which can be determined by
umask. Let us assume that the file permission for the created file is -rw-r--r--. Using chmod
command, we can change the file permissions and allow the owner to execute his file. The
command can be used in two ways:
5.1 In a relative manner by specifying the changes to the current permissions
5.2 In an absolute manner by specifying the final permissions
5.1 RELATIVE PERMISSIONS
chmod only changes the permissions specified in the command line and leaves the other permissions
unchanged.
Its syntax is:
chmod category operation permission filename(s)
chmod takes an expression as its argument which
contains: user category (user, group, others)
operation to be performed (assign or remove a
permission) type of permission (read, write, execute)
The below shows the abbreviations used by chmod command
Category operation permission
u - user + assign r - read
g – group - remove w - write
o - others = absolute x-
execute a - all (ugo)
Ex 1:
$ls –l xstart
-rw-r--r-- 1 kumar metal 1906 sep 23:38
xstart Here user is having the only read and execute
permission .
Using relative file permission need to add the execute permission to user
chmod category operation(+,-) permission filename.
$chmod u + x xstart
$chmod u+x xstart
$ ls –l xstart
-rwxr--r-- 1 kumar metal 1906 sep 23:38 xstart
After executing the chmod command, the command assigns (+) execute (x) permission to the user
(u), other permissions remain unchanged.
Ex 2: To remove execute permission from all and assign read permission to group and others
$chmod a-x, go+r xstart /*to remove execute permission from all(a)ie user, group, others
/*to assign read permission to group and others (go+r)
Ex 3: To assign write and execute permissions for others.
$chmod o+wx xstart
5.2 ABSOLUTE PERMISSIONS
A string of three octal digits is used as an expression. The permission can be represented by one
octal digit for each category. For each category, we add octal digits. If we represent the
permissions of each category by one octal digit, this is how the permission can be represented:
Read permission – 4 (octal 100)
Write permission – 2 (octal 010)
Execute permission – 1 (octal 001)
Octal Permissions Significance
0 --- no permissions
1 --x execute only
2 -w- write only
3 -wx write and execute
4 r-- read only
5 r-x read and execute
6 rw- read and write
7 rwx read, write and execute
We have three categories and three permissions for each category, so three octal digits can
describe a file’s permissions completely. The most significant digit represents user and the least
one represents others. chmod can use this three-digit string as the expression.
Ex 1: To assign read,write permissions to all .Using relative permission, we have,
$chmod a+rw xstart
Using absolute permission, we have,
$chmod 666 xstart /* 6 for r-w
/* first digit 6 for user, second 6 for group and third 6 for other
Ex 2:
To assign read and write for user and remove write, execute permissions from group and others
Here to assign rw- corresponds to digit 6
Remove write , execute permissions is nothing but assigning only read option to group and
oth- ers
Only read permission is r—corresponds to 4
$chmod 644 xstart
Ex 3:
To assign all permissions to the owner, read and write to group and only execute for others.
$chmod 761 xstart
Ex 4
To assign all permissions to all categories.
$chmod 777 xstart
5.3 The Security Implications
Let the default permission for the file xstart is
-rw-r—r--
$chmod u-rw, go-r xstart or
$chmod 000 xstart
After Executing above any one command the output will be removes the all permission from all
categories as shown below
----------
This is simply useless but still the user can delete
this file On the other hand,
chmod a+rwx xstart or
chmod 777 xstart
After Executing either of the one command it adds the all permission to all categories as
shown below
-rwxrwxrwx
The UNIX system by default, never allows this situation as you can never have a secure system.
Hence, directory permissions also play a very vital role here.
5.4 use chmod Recursively.(-R)
It possible to make chmod descend directory hierarchy and apply the expression to every
file and sub directory it finds. This is done by using -R option
$chmod -R a+x shell_scripts
This makes all the files and subdirectories found in the shell_scripts directory, executable by all users.
6. DIRECTORY PERMISSIONS
Directories also have their own permissions and the significance of these permissions
differ from those of ordinary files.
The default permissions of a directory are,
rwxr-xr-x (755)
A directory must never be writable by group and others
Ex1:
$mkdir c_progs ; ls –ld c_progs
drwxr-xr-x 2 kumar metal 512 may 9 09:57 c_progs
Here the c_progs directory is created (mkdir c_progs) and then the attributes of directory is listed out(ls–
ld c_progs)
If a directory has write permission for group and others also, be assured that every user can
remove every file in the directory. As a rule, you must not make directories universally writable
unless you have definite reasons to do so.
7. CHANGING FILE OWNERSHIP
There are two commands meant to change the ownership of a file or directory.
chown changing file owner and
chgrp changing group owner
7.1 chown : Changing file owner
The syntax is
chown options owner [:group] file(s)
For changing ownership requires super user permission. So let’s first change our status to
that of super user with the su command:
$su
Password:
****** #_
After the password is successfully entered, su returns a # prompt, the prompt used by root. su lets
us acquire super user status if we know the root password.
Consider the file note owned by kumar.To now renounce the ownership of the file note to Shar-
ma, use chown in the following way:
# ls -l note
-rwxr----x 1 kumar metal 347 may 10 20:30 note
#chown sharma note; ls -l note
-rwxr----x 1 sharma metal 347 may 10 20:30 note
Once ownership of the file has been given away to sharma, the user file permissions that
previously applied to Kumar now apply to sharma. Thus, Kumar can no longer edit note since
there is no write privilege for group and others. He cannot get back the ownership either. But he
can copy the file to his own directory, in which case he becomes the owner of the copy.
7.2 chgrp :Changing Group Owner
This command changes the file’s group owner. No superuser permission is required.
$ ls –l dept.lst
-rw-r--r-- 1 kumar metal 139 jun 8 16:43 dept.lst Here the group
owner of dept.lst is metal
$chgrp dba dept.lst; ls –l dept.lst
-rw-r--r-- 1 kumar dba 139 jun 8 16:43 dept.lst
The group owner of the file dept.lst is changed from metal to dba by issuing the command
$chgrp dba dept.lst
The file attributes of dept.lst is listed by issuing the command
$ls –l dept.lst
Using chown to change both file owner and group : The syntax requires two arguments to be
separated by : chown sharma:dba dept.lst
Here the ownership of dept.lst is changed to sharma and group to dba
More File Attributes:
1. File Systems and Inodes
• A file system is the structure used to store and organize files on a disk.
• Every file in UNIX is represented by an inode (index node).
• An inode stores metadata about a file, such as:
o File type (regular file, directory, etc.)
o File permissions
o Ownership (user ID and group ID)
o Timestamps (modification, access, and change time)
o Number of hard links
o File size
o Location of file data blocks (but not the filename)
• The filename is stored separately in a directory entry, which maps to the inode.
2. Hard Links
A hard link is a directory entry that associates a filename with an existing inode (file
metadata). Multiple hard links can point to the same inode, meaning they share the same
data blocks on disk.
Characteristics of Hard Links
• Same Inode Number → Hard links share the same inode as the original file.
• Same Data → Modifying one file updates all hard links pointing to it.
• Does Not Depend on Original File → Even if the original file is deleted, hard links
still retain the data.
• Cannot Span Across File Systems → Hard links must be on the same partition.
• Cannot Be Created for Directories → Only works for regular files (unless you
have superuser permissions).
Where to Use Hard Links – Explanation
Hard links are useful in various scenarios where you need to reference the same file multiple
times without duplicating its content.
1. When You Move Files, Creating Links Solves Problems for Programs Referencing the
File
Issue: Some programs reference specific file paths. If a file is moved, the program might
not find it.
Solution: Creating a hard link ensures that even if the file is moved within the same
filesystem, programs can still access it.
Example:
Suppose a script is referencing /home/user/data/report.txt, but you need to move the file to
/home/user/documents/. Instead of breaking the script, create a hard link:
ln /home/user/data/report.txt /home/user/documents/report.txt
Now, the file remains accessible from both locations.
When You Accidentally Delete a File
Issue: If you delete a file, it's lost unless you have a backup.
Solution: If a hard link exists, the file remains accessible.
Example:
If important.doc is linked:
ln important.doc backup_important.doc
Even if important.doc is deleted, backup_important.doc still contains the data
Avoid Maintaining Two Programs with Minor Differences
Issue: If you have two versions of a program with small changes, maintaining them
separately leads to redundancy.
Solution: Use hard links to reference the same base file while maintaining separate
configurations or minor modifications.
Example:
Suppose you have a script script_v1.sh, and you need a slightly modified version script_v2.sh:
ln script_v1.sh script_v2.sh
• Both files reference the same inode, so any changes made in one reflect in the other.
3. Symbolic (Soft) Links
A symbolic link (soft link) is a special type of file that points to another file or directory.
Unlike hard links, a symbolic link does not contain the actual file data but just a reference to
the target file's path.
Key Features:
Can point to files or directories
Can span different filesystems
If the original file is deleted, the symbolic link breaks (becomes a "dangling link")
Creating Symbolic Links with ln -s
The ln command is used to create both hard and symbolic links in Linux.
Syntax:
ln -s <target_file> <link_name>
• -s → Creates a symbolic (soft) link
<target_file> → The original file or directory
<link_name> → The name of the symbolic link
Example Usage of Symbolic Links
Creating a Symbolic Link to a File:
ln -s /home/user/original.txt shortcut.txt
Now, shortcut.txt points to original.txt
Creating a Symbolic Link to a Directory:
ln -s /var/logs logs_link
logs_link will point to /var/logs
Checking Symbolic Links:
ls -l
Output:
lrwxrwxrwx 1 user user 12 Mar 18 10:00 shortcut.txt -> /home/user/original.txt
Removing a Symbolic Link:
rm shortcut.txt
The link is removed, but the original file remains.
5. umask (User Mask)
• umask defines default file permissions for newly created files/directories.
• It works by subtracting values from the default permissions (666 for files, 777 for
directories).
• Example:
• umask 022
o Default file permissions = 666 - 022 = 644 (rw-r--r--)
o Default directory permissions = 777 - 022 = 755 (rwxr-xr-x)
• To check the current umask:
• umask
6. File Modification & Access Times
Every file has three timestamps:
1. Access time (atime) – Last time the file was read.
2. Modification time (mtime) – Last time the file content was modified.
3. Change time (ctime) – Last time metadata (permissions, owner, etc.) was modified.
Commands to check timestamps:
• ls -l → Shows mtime (modification time).
• stat filename → Shows all three timestamps.
To update timestamps:
• Modify access & modification times to current time:
• touch filename
• Set a specific timestamp:
• touch -t YYYYMMDDHHMM filename
(e.g., touch -t 202403281230 file1 sets time to March 28, 2024, 12:30 PM)