You are on page 1of 35

Network & System Administration Via Open

Source(Ubuntu)

Chapter-02: Directory and File Handling Commands


Directory and File Handling Commands

pwd (print [current] working directory)


✓ pwd displays the full absolute path to the your current location in the filesystem.
$ pwd
/usr/bin implies that /usr/bin is the current working directory.
ls (list directory)
✓ ls lists the contents of a directory. If no target directory is given, then the contents of
the current working directory are displayed.
$ ls
bin dev home mnt share usr var boot etc lib proc sbin tmp vol
✓ Actually, ls doesn't show you all the entries in a directory - files and directories that
begin with a dot (.) are hidden (this includes the directories '.' and '..' which are always
present).
Directory and File Handling Commands

cd (change [current working] directory)

$ cd path

✓ changes your current working directory to path (which can be an absolute or a


relative path).

✓ One of the most common relative paths to use is '..' (i.e. the parent directory of the
current directory).

mkdir (make directory)

$ mkdir directory

✓ creates a subdirectory called directory in the current working directory. .


Directory and File Handling Commands

rmdir (remove directory) rmdir cannot remove directories that have files or
directories in them. To do that, you must use the rm
$ rmdir directory command rm -rf [directory name]

✓ removes the subdirectory directory from the current working directory. You can only
remove subdirectories if they are completely empty (i.e. of all entries besides the '.'
and '..' directories).

cp (copy)

✓ cp is used to make copies of files or entire directories.

✓ To copy files, use:

$ cp source-file(s) destination

✓ where source-file(s) and destination specify the source and destination of the copy
respectively
Directory and File Handling Commands

cat (catenate/type)
$ cat target-file(s)
✓ displays the contents of target-file(s) on the screen, one after the other.
✓ You can also use it to create files from keyboard input as follows (> is the output
redirection operator:
$ cat > hello.txt
hello world!
[ctrl-d]
$ ls hello.txt
hello.txt
$ cat hello.txt
hello world!
$
Directory and File Handling Commands

more and less (catenate with pause)


$ more target-file(s)
✓ displays the contents of target-file(s) on the screen, pausing at the end of each
screenful and asking the user to press a key (useful for long files).
✓ It also incorporates a searching facility (press '/' and then type a phrase that you want
to look for).
✓ You can also use more to break up the output of commands that produce more than
one screenful of output as follows :
✓ $ ls -l | more
✓ less is just like more, except that has a few extra features (such as allowing users to
scroll backwards and forwards through the displayed file).
✓ less not a standard utility, however and may not be present on all UNIX systems.
Making Hard and Soft (Symbolic) Links

✓ Direct (hard) and indirect (soft or symbolic) links from one file or directory to another
can be created using the ln command.
$ ln filename linkname
✓ creates another directory entry for filename called linkname (i.e. linkname is a hard link).
✓ Both directory entries appear identical (and both now have a link count of 2).
✓ If either filename or linkname is modified, the change will be reflected in the other file
(since they are in fact just two different directory entries pointing to the same file).
$ ln -s filename linkname
✓ creates a shortcut called linkname (i.e. linkname is a soft link).
✓ The shortcut appears as an entry with a special type ('l'):
$ ln -s hello.txt bye.txt
$ ls -l bye.txt
lrwxrwxrwx 1 will financ e13 bye.txt -> hello.txt
$
Inspecting File Content

file filename(s)
✓ file analyzes a file's contents for you and reports a high-level description of
what type of file it appears to be:
$ file myprog.c letter.txt webpage.html
myprog.c: C program text
letter.txt: English text
webpage.html: HTML document text
head, tail filename
✓ head and tail display the first and last few lines in a file respectively.
✓ You can specify the number of lines as an option, e.g.
$ tail -20 messages.txt
$ head -5 messages.txt
Inspecting File Content

✓ tail includes a useful -f option that can be used to continuously monitor the last
few lines of a (possibly changing) file.
✓ This can be used to monitor log files, for example:
$ tail -f /var/log/messages
✓ continuously outputs the latest additions to the system log file.
Finding Files

find
$ find directory -name targetfile -print
✓ find will look for a file called targetfile in any part of the directory tree rooted at
directory. targetfile can include wildcard characters. For example:
$ find /home -name "*.txt" -print 2>/dev/null
✓ will search all user directories for any file ending in ".txt" and output any
matching files (with a full absolute or relative path).
✓ Here the quotes (") are necessary to avoid filename expansion,
Finding Files

find
✓ It can find files
➢ by type (e.g. -type f for files, -type d for directories),
➢ by permissions (e.g. -perm o=r for all files and directories that can be
read by others),
➢ by size (-size) etc.
✓ For more information about find and its abilities, use man find and/or info
find.
Finding Files

find
✓ The "find" command in Ubuntu is a powerful tool used to search for files and
directories based on various criteria.
✓ It allows you to locate files by their names, types, sizes, permissions, and more.
Here's how you can use the "find" command:

✓ Basic syntax: The basic syntax of the "find" command is as follows:


find [path] [expression]
✓ Searching by name: To find a file by its name, you can use the "-name" option followed by the
name or pattern you want to search for. For example:
find /home -name myfile.txt
Searching by type: You can search for files based on their type using the "-type" option. For
instance, to find all directories, you can use:
find / -type d
Finding Files

find
✓ Searching by size: The "-size" option allows you to search for files based on their size.
You can specify the size using different units such as "k" (kilobytes), "M" (megabytes),
or "G" (gigabytes). For example, to find files larger than 10MB:
find / -size +10M
✓ Combining search criteria: You can combine multiple search criteria using logical
operators like "and" (-a), "or" (-o), and "not" (!). For example, to find all files with a
".txt" extension in the "/home" directory and its subdirectories:
find /home -name "*.txt"
✓ These are just a few examples of how you can use the "find" command in Ubuntu. It
provides many more options and possibilities for searching files and directories. Feel
free to explore the manual page for more details by running the command man find.
Finding Files

which (sometimes also called whence) command


✓ If you can execute an application program or system utility by typing its name at the
shell prompt, you can use which to find out where it is stored on disk.
✓ For example:
$ which ls
/bin/ls

Whereis

✓ The whereis command will display the location of a command executable, as well as
its source and documentation, if available.
Finding Text in files

grep (General Regular Expression Print)


$ grep options pattern files
✓ grep searches the named files for lines that match a given pattern.
✓ The default behaviour of grep is to print out the matching lines. For example:
$ grep hello *.txt grep / read* *.txt
✓ searches all text files in the current directory for lines containing "hello".
✓ Some of the more useful options that grep provides are:
➢ -c (print a count of the number of lines that match),
➢ -i (ignore case),
➢ -v (print out the lines that don't match the pattern) and
➢ -n (printout the line number before printing the matching line). So
$ grep -vi hello *.txt
✓ searches all text files in the current directory for lines that do not contain any form of
the word hello (e.g. Hello, HELLO, or hELlO).
Finding Text in files

✓ If you want to search all files in an entire directory tree for a particular pattern, you can
combine grep with find using backward single quotes to pass the output from
find into grep.
✓ So
$ grep hello `find . -name "*.txt" -print`
✓ will search all text files in the directory tree rooted at the current directory for lines
containing the word "hello".
Sorting files

sort filenames
✓ sort sorts lines contained in a group of files alphabetically numerically.
✓ The sorted output is displayed on the screen, and may be stored in another file by
redirecting the output. So
$ sort input1.txt input2.txt > output.txt
✓ outputs the sorted concatenation of files input1.txt and input2.txt to the
file output.txt.
File Compression and Backup

tar (tape archiver)


✓ tar backs up entire directories and files onto a tape device or (more commonly)
into a single disk file known as an archive.
✓ An archive is a file that contains other files plus information about them, such as
their filename, owner, timestamps, and access permissions.
✓ tar does not perform any compression by default.
✓ To create a disk file tar archive, use
$ tar -cvf archivename filenames
✓ To list the contents of a tar archive, use
$ tar -tvf archivename
File Compression and Backup

tar (tape archiver)


✓ You have:notes_1.txt, notes_2.txt, notes_3.txt,
notes_4.txt, notes_5.txt
✓ You want to back them up and keep them on a USB deive,
tar -cvf linux_notes.tar notes*.txt
✓ First, you have tar, the name of the program. Then you
have the options, c (--create) v (--verbose-show what
files they are) (f--file -make a file - should always be
the last option)
✓ Then you have the name of the file you want to create (
linux_notes.tar) and the files you want to backup
(notes*.txt).
File Compression and Backup

tar (tape archiver)


tar -cvf bob_backup.tar *
✓ With one asterisk, you will include directories and
files without extensions .
✓ To list the contents of a tar archive, use
$ tar -tvf archivename
✓ This is the first step in the backup process.
✓ Now let's look at the second step; the compression of
these files.
File Compression and Backup

Using 'gzip'
✓ 'tar' just assembles the files together into only one
file. There is no reduction in the size of these files
✓ Now we would have to do one more thing in order to
reduce this file into a more manageable size: use
'gzip'.
✓ gzip is the preferred compression tool for Linux.
✓ To reduce the size of your tar file, you would issue the
following command:
$ gzip your_tar_file.tar
✓ The result would be a file like this:
your_tar_file.tar.gz
Redirecting input and output

✓ The output from programs is usually written to the screen, while their input usually
comes from the + (if no file arguments are given).
✓ In technical terms, we say that processes usually write to standard output (the screen)
and take their input from standard input (the keyboard).
✓ There is in fact another output channel called standard error, where processes write
their error messages; by default error messages are also sent to the screen.
✓ To redirect standard output to a file instead of the screen, we use the > operator:
$ echo hello
hello
$ echo hello > output
$ cat output
hello
✓ In this case, the contents of the file output will be destroyed if the file already
exists.
Redirecting input and output

✓ If instead we want to append the output of the echo command to the file, we can use
the >> operator:
$ echo bye >> output
$ cat output
hello
bye
✓ To capture standard error, prefix the > operator with a 2 (in UNIX the file
numbers 0, 1 and 2 are assigned to standard input, standard output and standard error
respectively), e.g.:
$ cat nonexistent 2>errors
$ cat errors
cat: nonexistent: No such file or directory
$
Redirecting input and output

✓ You can redirect standard error and standard output to two different files:
$ find . -print 1>outputfile 2>errorfiles
✓ or to the same file:
$ find . -print 1>output 2>output
✓ Standard input can also be redirected using the < operator, so that input is read
from a file instead of the keyboard:
$ cat < existing_file
hello
Bye
File and Directory Permissions

✓ In this section we'll learn about how to set Linux permissions on files and directories.
✓ Permissions specify what a particular person may or may not do with respect to a file
or directory.
✓ Linux permissions dictate 3 things you may do with a file, read, write and execute.
✓ They are referred to in Linux by a single letter each.
➢ r read - you may view the contents of the file.
➢ w write - you may change the contents of the file.
➢ x execute - you may execute or run the file if it is a program or script.
✓ For every file we define 3 sets of people for whom we may specify permissions.
➢ owner - a single person who owns the file. (typically the person who created
the file but ownership may be granted to some one else by certain users)
➢ group - every file belongs to a single group.
➢ others - everyone else who is not in the group or the owner.
File and Directory Permissions

View Permissions
✓ To view permissions for a file we use the long listing option for the command ls.
Ls –l [path]
g24@Ubuntu:~$ ls -l /home/ryan/linuxtutorialwork/frog.png

-rwxr----x 1 harry users 2.7K Jan 4 07:32 …frog.png

✓ In the above example the first 10 characters of the output are what we look at to identify
permissions.

✓ - rwx r-- --x 1 harry users 2.7K Jan 4 07:32 …frog.png

➢ The first character identifies the file type. If it is a dash ( - ) then it is a normal
file. If it is a d then it is a directory.
File and Directory Permissions

- rwx r-- --x 1 harry users 2.7K Jan 4 07:32 ../frog.png

➢ The following 3 characters represent the permissions for the owner. A letter represents
the presence of a permission and a dash ( - ) represents the absence of a permission.
In this example the owner has all permissions (read, write and execute).

- rwx r-- --x 1 harry users 2.7K Jan 4 07:32 ../frog.png

➢ The following 3 characters represent the permissions for the group. In this example the
group has the ability to read but not write or execute.

Note that the order of permissions is always read, then write then execute.

- rwx r-- --x 1 harry users 2.7K Jan 4 07:32 ../frog.png

➢ Finally the last 3 characters represent the permissions for others (or everyone else). In
this example they have the execute permission and nothing else.
File and Directory Permissions

Change Permissions

✓ To change permissions on a file or directory we use a command called chmod It stands


for change file mode bits which is a bit of a mouthfull but think of the mode bits as the
permission indicator

Chmod [permissions] [path]

✓ chmod has permission arguments that are made up of 3 components

➢ Who are we changing the permission for? [ugoa] - user (or owner), group,
others, all

➢ Are we granting or revoking the permission - indicated with either a plus ( + )


or minus ( - )

➢ Which permission are we setting? - read ( r ), write ( w ) or execute ( x )


File and Directory Permissions

The following examples will make their usage clearer.

✓ Grant the execute permission to the group. Then remove the write permission for the
owner
File and Directory Permissions

Setting Permissions Shorthand

✓ To understand how this shorthand method works we first need a little background in
number systems…(Binary, Octal ,Decimal, Hexadecimal etc..)

✓ Now it just so happens that with 3 permissions and each being on or off, we have 8
possible combinations (2^3). And then we can also represent our numbers using
binary which only has 2 symbols (0 and 1).

✓ The mapping of octal to binary is in the table below.


File and Directory Permissions

Setting Permissions Shorthand

✓ So we have 3 bits and we also have 3 permissions.

✓ If you think of 1 as representing on and 0 as off then a single


octal number may be used to represent a set of permissions
for a set of people.

✓ Three numbers and we can specify permissions for the user,


group and others.
File and Directory Permissions

Setting Permissions Shorthand

✓ Let's see some examples. (refer to the table above to see how they match)

✓ 755 or 750 are commonly used for scripts.


File and Directory Permissions

Permissions for Directories

✓ The same series of permissions may be used for directories but they have a slightly
different behaviour.

➢ r - you have the ability to read the contents of the directory (ie do an ls).

➢ w - you have the ability to write into the directory (ie create files and
directories)

➢ x - you have the ability to enter that directory (ie cd)


File and Directory Permissions

Permissions for Directories

✓ Let's see some of these in action


Thanx !!!

You might also like