Loading...
Menu

Work with the Command-line: To manage files and directories in Ubuntu

 

Work with the Command-line: To manage files and directories in Ubuntu

 

Copyright 2017 Sudiman Suhaili

Published by Sudiman Suhaili at Shakespir

 

 

 

Shakespir Edition License Notes

This ebook is licensed for your personal enjoyment only. This ebook may not be re-sold or given away to other people. If you would like to share this book with another person, please purchase an additional copy for each recipient. If you’re reading this book and did not purchase it, or it was not purchased for your enjoyment only, then please return to Shakespir.com or your favorite retailer and purchase your own copy. Thank you for respecting the hard work of this author.

 

 

 

 

Table of Contents

Acknowledgements

Chapter 1 – Introduction to Linux

1.1 – Understand Linux

1.2 – Describe Linux Distributions

1.3 – Overview of Ubuntu

1.4 – Describe Linux Directory Structure

1.5 – Understand the Filesystem Hierarchy Standard (FHS)

1.6 – Explain the pathnames

Chapter 2 – Command Shell

2.1 – Understand CLI

2.2 – Access the command-line

2.3 – Overview of BASH shell

2.4 – Understand and execute Linux commands

2.5 – Identify types of command

2.6 – Get command-line helps

Chapter 3 – Files & Directories

3.1 – Navigate directory tree

3.2 – Work with files and directories

3.3 – Search files

3.4 – View files contents

3.5 – Search file contents

Chapter 4 – File & Directory Permissions

4.1 – Understand files ownership and permission

4.2 – Change files permissions

4.3 – Describe and set up special permissions

4.4 – Understand default permissions

About Sudiman Suhaili

Connect with Sudiman Suhaili

 

 

 

 

Acknowledgements

This book is aimed at anybody who are looking to deepen their understanding of the command-line in Linux, the essential skills to use and manage the operating system. This book also an ideal reference for beginners to learn the common and basic Linux commands but it is also great for intermediate users.

In this book, we use the Ubuntu to understand how Linux can be used, explore the Linux directory tree and work on the command-line to perform various tasks related to manage files and directories in the system. Most of the examples in this book are accomplished in the Ubuntu LTS. However, all the commands in this book are generally can be applied in most Linux distributions.

 

Chapter 1


table>. >. |>/2.
p>{color:#000;}.  

|>. p={color:#000;}.  
>.

 

In this chapter, you will be introduced to Linux, including an overview of the most well-known Linux distribution – Ubuntu. You also learn about the structure of Linux directory tree and how to describe files or directories using pathnames.

 

Objective:

*
p<>{color:#000;}. Understand Linux

*
p<>{color:#000;}. Describe Linux Distributions

*
p<>{color:#000;}. Overview of Ubuntu

*
p<>{color:#000;}. Describe Linux Directory Structure

*
p<>{color:#000;}. Understand the Filesystem Hierarchy Standard (FHS)

*
p<>{color:#000;}. Explain the pathnames

 

1.1 Understand Linux

Linux is a UNIX-like free and open source operating system. It manages computer hardware and software for the users. Linux uses the same concepts and basic idea as UNIX operating system. Linux is available in source code form that permits users to use, study and change or improves it.

An operating system consists of a kernel and some system programs and some application programs for doing work. More precisely, Linux is a kernel, which is the core of Linux operating system. But it is pretty common to refer the entire operating system as Linux. This kernel acts as the intermediary between the applications which run in the operating system and the underlying hardware. Linux kernel provides basic services for all other parts of the operating system.

table=. =. |=.
p={color:#000;}.

|

Figure 1.1 1 Operating System Kernel

Free software sometimes referred to as “libre software” to avoid the potential confusion between the intended meanings of “free” meaning freedom and “free” meaning at no cost. The term free is equal to freedom, not price, there might still exist some confusion in the use of this term. Some people suggest that “open source” has replaced the term “free software”, while others still cannot see the relation between free and open.

The term FOSS (Free and Open Source Software) or FLOSS (Free/Libre and open Source Software) embraces the benefits and adherents of both paradigms, free software and open source software. However, all these terms are referred to the software released under a license that permits the inspection, use, modification and redistribution of the source code.

GNU/Linux is the preferred term advanced by Richard Stallman and the Free Software Foundation (FSF). GNU Project was to develop the GNU operating system composed wholly of free software. It was initiated by Richard Stallman on 1983. Linux kernel was developed by Linus Torvalds and released under the GPL license as a free software. The combination of Linux kernel and additional software from GNU Project was produced the operating system composed completely of free software.

 

1.2 Describe Linux Distributions

Linux flavours is known as Linux distribution or just called as “distro”. Linux distribution comprises a Linux kernel, GNU tools and libraries, additional software, documentation and/or a desktop environment to perform as a complete operating system.

table=. =. |=.
p={color:#000;}.

|

Figure 1.2 2 Several Linux distribution logos

Even though the Linux kernel is at the heart of every distribution, many distributions also use different default software, package managers, configuration utilities and other software.

Some Linux distributions refuse to include closed-source (proprietary) software, while others include closed-source software to make it easier on users. Some distributions are bleeding edge and would not receive support for very long time, while others are designed to be stable distributions that will be supported with security updates and bug fixes for many years.

Some distributions are maintained by a community of volunteers, while others are backed by companies that charge fees for subscriptions and supports. Some distributions are designed to run on laptops and desktops, while others are designed to run on servers. You can get the list of the most important Linux distribution from the DistroWatch website (https://distrowatch.com).

 

1.3 Overview of Ubuntu

Ubuntu is one of the most famous Linux distributions, published by Canonical Ltd., offering both community and commercial support. “Ubuntu” is an ancient African word, meaning “humanity to others”. Ubuntu was first released in 2004, Ubuntu consists of many software packages, which are licensed under open source licenses. This allows users to copy, change, develop and redistribute their own version of the program. There is also proprietary software that can be run on Ubuntu. Ubuntu has several versions of its distribution for different environments.

table=. =. |=.
p={color:#000;}. Ubuntu |=.
p={color:#000;}. Descriptions | =. |=.
p={color:#000;}. Desktop |=.
p={color:#000;}. This is the traditional version of the distro, which is designed for workstations, desktop and laptop using Unity desktop interface.

| =. |=. p={color:#000;}. Server |=. p={color:#000;}. This version is designed for servers, so it is a task-oriented one with no desktop environment installed by default. | =. |=. p={color:#000;}. Cloud |=. p={color:#000;}. This version is installed in servers to create public cloud computing environment, having a complete OpenStack product and compatible as images for the most common public clouds such as Amazon AWS, Google Cloud and MS Azure. | =. |=. p={color:#000;}. Kylin |=. p={color:#000;}. This is the desktop version for the China market and it complies with the Chinese government’s procurement regulations. | =. |=. p={color:#000;}. Phone (Mobile) |=. p={color:#000;}. This version is installed in smartphones and tablets, but not available for download from the web site. |

Table 1.3 1 Ubuntu versions

Ubuntu releases are published in a time based fashion, every six months, following a planned schedule. It is using the year and month of the release as a version number. For example, Ubuntu 16.10 was released on October 2016. Releases 6.06, 8.04, 10.04, 12.04, 14.04, and 16.04 are the LTS releases. LTS is an abbreviation for “Long Term Support” released every two years. Standard Ubuntu releases are supported for nine months and Ubuntu LTS releases are supported for five years on both the desktop and server. During that time, there will be security fixes and other critical updates.

Figure 1.3 3 Ubuntu support lifecycle (www.ubuntu.com)

 

1.4 Describe Linux Directory Structure

In Linux, the directory (or folder) begins with the root directory, which contains a number of sub-directories in it. Each sub-directory contains several sub-directories of their own, thus creating a directory hierarchy. All storage devices are connected to the filesystem hierarchy. Different physical or virtual storage devices are invisible to the user since all files and directories appear under the root directory. Slashes (/) are used to separate directory names in Linux.

The Linux directory tree structure contains a single root (referred to using the forward-slash / character), with different filesystems on hard drive partitions mounted (or attached) to different directories on this directory tree.

The Figure 1.4-4 is an example of implementation of single-root directory hierarchy in Linux, with the presence of the home directory as mount point for the other partition or filesystem attached to the main filesystem:

table=. =. |=.
p={color:#000;}.

|

Figure 1.4 4 Example of directory tree in Linux

While in Windows, each partition on a hard disk is referred to by a drive letter (such as C: or D:). Each of them has a root directory (indicated by the back-slash \ character) containing sub-directories that together form a hierarchical tree.

The Figure 1.4-5 is an example of implementation of multiple-root (C: and D:) or multiple directory hierarchies in Windows.

table=. =. |=.
p={color:#000;}.

|

Figure 1.4 5 Example of directory tree in Windows with two drives

 

1.5 Understand the Filesystem Hierarchy Standard (FHS)

Linux distributions follow the Filesystem Hierarchy Standard (FHS) to define the directory structure and contents. It is maintained by the Linux Foundation. FHS helps you to simplify the task of finding specific files because the location of the essential and common files are same in most of different Linux distributions.

A comprehensive understanding of the standard types of directories found on Linux systems is valuable when locating and managing files and directories. Refer to Table 1.5-2 for some Linux directories defined by FHS and their descriptions.

=.
p={color:#000;}. Descriptions
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.

Table 1.5 2 Some of Linux directories defined by the FHS

 

1.6 Explain the pathnames

It is important to describe files or directories in the filesystem hierarchy by their proper pathnames. Pathname or path is a statement of the location of a file or directory in the filesystem hierarchy. It is a slash-separated list of directory names followed by either a directory name or a file name.

To refer to any file or directory, use either an absolute pathname or a relative pathname. You can use an absolute pathname from any location but if you want to use relative pathname you should be present in a directory where you are going to specify relative to that present working directory.

The /home/sudiman/Documents/note represents the absolute pathname to the note directory. The absolute pathname to a file or directory is the full pathname of a certain file or directory starting from the root directory (/) of the filesystem.

table=. =. |=.
p={color:#000;}.

|

Figure 1.6 6 The note directory in the system directory tree

A relative pathname is the pathname of a target file or directory relative to your current working directory. If the /home/sudiman is your current directory, you could simply refer to the note directory as Documents/note. The pathname without a slash at the begin means that the current directory is the starting point.

 

Chapter 2


table>. >. |>/2.
p>{color:#000;}.  

|>. p={color:#000;}.  
>.

 

For daily use, Ubuntu is very easy and comprehensive without the use of the command-line. However, the command-line is a convenient way to perform many extremely powerful operations that are rather difficult to express graphically. This chapter will introduce the use of command shell on Linux system. You will learn the BASH shell and the fundamental of Linux commands.

 

Objective:

*
p<>{color:#000;}. Understand command-line interface (CLI)

*
p<>{color:#000;}. Access the command-line

*
p<>{color:#000;}. Overview of BASH shell

*
p<>{color:#000;}. Understand and execute Linux commands

*
p<>{color:#000;}. Get command-line helps

 

2.1 Understand CLI

To use Linux, you must log in to the system and interact with the kernel of the system’s to perform useful tasks. By default, you receive a command-line shell (e.g. BASH shell) when you log in to a terminal which provides an interface that passes your input to the kernel for processing. The command-line interface is often referred to by its abbreviation, CLI.

A shell is a program that accepts commands and instructs the Linux kernel what to do. The shell in this particular case is a command line interpreter and acts as your interface to the system. The most common shell you can find in Linux is BASH (Bourne-again shell).

Linux is a multiuser and multitasking operating system, which allows many different users logged in to the same Linux computer. As such, Linux can allow for many terminals with each terminal could represent a separate logged-in user that has its own shell. Users could be logged in locally to the computer and other users could be logged in across a network.

 

2.2 Access the command-line

When you log in to Ubuntu Server or any Linux system without the graphical user interface (GUI), a command-line shell is started and you are presented with a prompt. Figure 2.2-7 shows an example of login prompt in Ubuntu. If you log in to Ubuntu Desktop or a system that is in graphical mode, you will be interacting with a GUI. A graphical terminal login for Ubuntu Desktop is depicted in Figure 2.2-8.

table=. =. |=.
p={color:#000;}.

|

Figure 2.2 7 Terminal login prompt

In order to access the command-line while logged into a GUI environment, you will need to start a terminal emulator application (also known as terminal window). Common terminal emulators include xterm, GNOME Terminal, KDE Konsole, rxvt, and Eterm. In Ubuntu, the most common way is simply running terminal emulator from the Dash. This will launch GNOME Terminal as shown in Figure 2.2-9.

table=. =. |=.
p={color:#000;}.

|

Figure 2.2 8 Ubuntu Desktop login

To access a virtual terminal device at your local machine, you can press a combination of keys. For example, combination keys of Ctr+Alt+F2 will change to the second virtual terminal (tty2). A virtual terminal is a full-screen terminal which does not run inside GUI. After you are logged in to a command-line terminal, you receive a prompt where you can enter commands.

table<>. <>. |<>.
p={color:#000;}.

|

Figure 2.2 9 GNOME Terminal in Ubuntu

The line [email protected]:~$ from the preceding figure is the command prompt. The default prompt is different based on distributions and/or shell types. The command prompt displays the current logged in username, separated with an alias (@) sign from the computer’s hostname. A colon (:) separates the hostname from the current working directory, and finally a dollar sign ($) announces the end of the prompt. Your cursor shows up on the same line after the dollar sign, and your system waits for your command.

Shell sessions can generally be terminated using the exit command. This also applies to the shell that you obtained immediately after logging in (same as logout).

=.

 

2.3 Overview of BASH shell

Ubuntu as well as most other recent Linux distributions include BASH as default shell. BASH is a free software replacement for the Bourne shell (sh). BASH is a sh-compatible, also incorporates useful features from other shells (i.e., Korn and C shells). A BASH shell has several variables in memory at any one time, which are categorized as environment variables and user-defined variables.

The environment variables are typically set by default in the BASH shell and contain information about the system or that shell access regularly.

table=. =. |=.
p={color:#000;}. Variables |=.
p={color:#000;}. Contents | =. |=.
p={color:#000;}. BASH |=.
p={color:#000;}. The full path to the BASH shell.

| =. |=. p={color:#000;}. BASH_VERSION |=. p={color:#000;}. The version of the current BASH shell. | =. |=. p={color:#000;}. CDPATH

 

|=. p={color:#000;}. The colon-separated list of directories used as a search path for the cd built-in command. | =. |=. p={color:#000;}. ENV |=. p={color:#000;}. The location of the BASH run-time configuration file. | =. |=. p={color:#000;}. EUID |=. p={color:#000;}. The effective UID (User ID) of the current user. | =. |=. p={color:#000;}. HISTFILE |=. p={color:#000;}. The file to store previously entered commands. | =. |=. p={color:#000;}. HOME |=. p={color:#000;}. The absolute path name of the current user’s home directory. | =. |=. p={color:#000;}. HOSTNAME |=. p={color:#000;}. The host name of the Linux system. | =. |=. p={color:#000;}. LOGNAME |=. p={color:#000;}. The current user used when logging in to the shell. | =. |=. p={color:#000;}. MAIL |=. p={color:#000;}. The location of the mailbox file (where e-mail is stored). | =. |=. p={color:#000;}. OSTYPE |=. p={color:#000;}. The current operating system. | =. |=. p={color:#000;}. PATH |=. p={color:#000;}. The directories to search for executable program files. | =. |=. p={color:#000;}. PS1 |=. p={color:#000;}. The current shell prompt. | =. |=. p={color:#000;}. PS2 |=. p={color:#000;}. The secondary shell prompt. | =. |=. p={color:#000;}. PWD |=. p={color:#000;}. The current working directory. | =. |=. p={color:#000;}. RANDOM |=. p={color:#000;}. The variable that creates a random number when accessed. | =. |=. p={color:#000;}. SHELL |=. p={color:#000;}. The absolute path name of the current shell. | =. |=. p={color:#000;}. TERM |=. p={color:#000;}. The variable used to determine the terminal settings. |

Table 2.3 3 Common BASH environment variables

Table 2.3-3 provides a list of common environment variables used in BASH shell. To view the contents of a variable, you can use the echo command and specify the variable name prefixed by the $ metacharacter, as shown in the following output:

=.
=.

The user-defined variables are created by users. When creating new user-defined variable identifiers (name of variables), it is important to note the following rules and conventions:

*
p<>{color:#000;}. They can contain alphanumeric characters (0–9, A–Z, a–z), the dash (-) or the underscore (_) characters.

*
p<>{color:#000;}. They must not start with a number.

*
p<>{color:#000;}. They are typically capitalized.

=.
=.
=.
=.

There are other variables to perform special function in the shell. For examples, umask variable determines the settings of a mask that controls how file permissions are set for newly created files and alias variable stores the aliases (shortcuts to commands).

table=. =. |=.
p={color:#000;}. To create an alias to the command rm -rf called allremove[_:_] | =. |=.
p={color:#000;}. [email protected]:~$ alias allremove="rm -rf" | =. |=.
p={color:#000;}. Then, view the alias variable contents: | =. |=.
p={color:#000;}. [email protected]:~$ alias | =. |=.
p={color:#000;}. alias allremove=‘rm -rf'

alias egrep=‘egrep --color=auto’

alias fgrep=‘fgrep --color=auto’

alias grep=‘grep --color=auto’

alias l=‘ls -CF'

alias la='ls -A'

alias ll=‘ls -alF’

alias ls=‘ls --color=auto’ |

To ensure that all variables are accessible to a shell at all times, you must place variables in the environment files. The common BASH environment files and the order in which they are typically executed are as follows:

*
p<>{color:#000;}. The /etc/profile file is the system wide initialization file and executed after login for all users on the system and sets most environment variables

*
p<>{color:#000;}. The /etc/bashrc file is the system wide runtime configuration file is used to set aliases and variables that must be present in the BASH shell for all users.

*
p<>{color:#000;}. The personal runtime configuration file ~/.bashrc is used to set aliases and variables for a specific user.

*
p<>{color:#000;}. The hidden environment files ~/.bash_login, ~/.bash_profile and ~/.profile are executed to set environment variables for a specific user.

Any values assigned to variables in the ~/.bash_login, ~/.bash_profile and ~/.profile files override those set in /etc/profile, /etc/bashrc and ~/.bashrc due to the order of execution.

 

2.4 Understand and execute Linux commands

A command is an instruction given by a user telling a computer to do something, such a run a single program or a group of linked programs. Linux commands are case-sensitive and are typically lowercase. Commands are generally issued by typing them in at the command-line and then pressing the Enter key, which passes them to the shell.

A command consists of a command name usually followed by one or more strings (i.e., sequences of characters) that comprise options and arguments. Each of these strings is separated by white space (which consists of one or more spaces or tabs). The general syntax for commands is:

command [options] [arguments]

An option, also sometimes referred to as a switch or a flag, is a single-letter code, or sometimes a single word or set of words, that modifies the behavior of a command in some predetermined way. When multiple single-letter options are used, all the letters are placed adjacent to each other (not separated by spaces) behind a single dash (-) and can be in any order. For example, the options sequence “ -a -l -F ” corresponds to “-alF”.

Many programs have more options than can be conveniently mapped to single characters, or support “long options” for readability (frequently in addition to equivalent single-character options). Long options most often start with two dashes and cannot be accumulated. For example, the command ls –aF is equivalent to ls --all --classify .

An argument is a string with no leading dash. It is often the file names or other data that is provided to a command in order for the command to use it as an input. The following is an example of command with two options (a, l) followed by an argument, pathname of the default directory.

ls -al /etc/default/

 

2.5 Identify types of command

Generally, a command we use in the command-line is built-in or external command. A built-in is a command or a function, called from a shell, which is executed directly in the shell itself. This type of command work significantly faster than external command. However, their code is inherently present in the shell, and thus modifying or updating them requires modifications to the shell. Some examples from BASH shell include cd, echo, and history. The help BASH-built-in command will list all built-ins. The following are examples on how to use file command to identify the type of commands:

=.
=.
=.
=.
=.

Note the output shows that help is built-in command. Meanwhile, the following output shows the pathname for mkdir to indicate that it is an external command.

An external command is external executable program which the shell would load and execute, which usually can be found in any Linux distribution. They mostly reside in /bin and /usr/bin, and those locations must be part of your PATH variable in order to be usable.

The PATH is a shell’s environmental variable in Linux system that tells the shell which directories to search for executable files or external commands in response to commands issued by a user. Directories in the path list are separated by colons. The path directory order is important. Directories are checked from left to right. For example, if there is command called “ohaa” located in both the /bin and /usr/bin directories, the one in /usr/bin is executed.

table=. =. |=.
p={color:#000;}. To view the PATH variable contents: | =. |=.
p={color:#000;}. [email protected]:~$ echo $PATH | =. |=.
p={color:#000;}. /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:

/bin:/usr/games:/usr/local/games:/snap/bin |

2.6 Get command-line helps

Linux stores documentation for each command in central locations so that it can be accessed easily. The most common form of documentation for Linux commands is manual pages (commonly referred to as man pages). Another utility is the GNU info pages, which provides easy-to-read description of each command and also contains links to other information pages (called hyperlinks).

The manual pages are a user manual that is by default built into most Linux distributions during installation. They provide extensive documentation about commands and other aspects of the system, including configuration files, system calls, library routines and the kernel. The basic syntax is:

man [option] [keywords or commands]

For example, you can use the following command:

=.

You can use the option –k to find all of the commands that match with specific strings.

table=. =. |=.
p={color:#000;}. To find all of the commands that have the word “usb”: | =. |=.
p={color:#000;}. [email protected]:~$ man –k usb | =. |=.
p={color:#000;}. lsusb (8) – list USB devices

update-usbids (8) – download new version of the USB ID list

usb-devices (1) – print USB device details

usbhid-dump (8) – dump USB HID device report descriptors

and streams |

The apropos command perform the same function as the man –k command. Both commands yield the exact same output on the terminal screen.

table=. =. |=.
p={color:#000;}. To view output of the apropos command related to the word “usb”: | =. |=.
p={color:#000;}. [email protected]:~$ apropos usb | =. |=.
p={color:#000;}. lsusb (8) – list USB devices

update-usbids (8) – download new version of the USB ID list

usb-devices (1) – print USB device details

usbhid-dump (8) – dump USB HID device report descriptors

and streams |

All manual pages contain certain section numbers that describe the category of the command in the manual page database.

=.
p={color:#000;}. Descriptions
=.
=.
=.
=.
=.
=.
=.
=.
=.

Table 2.6 4 Section numbers of manual pages

You can access this utility by typing the info command followed by the name of the command in question:

info [command]

An example of using the info command as follows:

=.

You can also display a brief help on a command (works with most commands) as following:

=.

Some commands do not have manual pages or info pages. These commands are usually functions that are built into the BASH shell itself. To find help on these commands, you must use the help command, as shown here:

=.

 

Chapter 3


table>. >. |>/2.
p>{color:#000;}.  

|>. p={color:#000;}.  
>.

 

Linux users must understand and able to perform the file and directory management tasks. This chapter will help you navigating directories and manipulating the files inside the Linux directory tree, create directories, copy or move files from one directory to another, and delete files and directories. You will also learn how to display the contents of the text files and search files or directories within directory tree.

 

Objective:

*
p<>{color:#000;}. Navigate directory tree

*
p<>{color:#000;}. View files contents

*
p<>{color:#000;}. Work with files and directories

*
p<>{color:#000;}. Find files

*
p<>{color:#000;}. Search file contents

 

3.1 Navigate directory tree

 

The most important services of an operating system like Linux consists of storing data on permanent and removable storage media and retrieving them later. A collection of data or information that has a name, called the filename. Almost all information stored in a computer must be in a file. On Linux, directories (also known as folders) are simply files, but you cannot access them using the same methods you would use for plain files. Directories may contain other directories, which results in a tree-like structure or also called as a directory tree.

The followings are several useful commands to navigate directory tree along with their description:

table=. =. |=.
p={color:#000;}. Commands |=.
p={color:#000;}. Descriptions | =. |=.
p={color:#000;}. pwd |=.
p={color:#000;}. Print name of the current working directory | =. |=.
p={color:#000;}. cd [directory] |=.
p={color:#000;}. Change the working directory | =. |=.
p={color:#000;}. cd or cd ~ |=.
p={color:#000;}. Return back to your home directory | =. |=.
p={color:#000;}. cd ..

=.
p={color:#000;}. To go to the parent directory
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.

Table 3.1 5 Common Linux commands to navigate directory tree

When you log into a Linux system, you are placed in your home directory as your current working directory. Regular users usually have a home directory named after their user name under the /home directory, as in /home/adam. However, the root user has a home directory called root under the root directory of the system (/root). You can always refer to your own home directory using the ~ metacharacter.

Look the pathname at the end of the shell prompt or run the pwd command at a command-line prompt to confirm the directory that you are currently in. This command displays the current working directory to your screen and allows you to keep track of where you are in the directory tree hierarchy.

The cd command changes the current directory to the specific directory. If cd is executed without specifying a directory, it changes the current directory to your home directory. The following is an example of how the pwd and cd commands can be used to navigate around the directory tree hierarchy.

=.
=.
=.
=.
=.
=.
=.
=.
=.
=.

The most common way to see the contents of a directory is to use the ls command. The ls command displays all the files in the current directory in columnar format.

table=. =. |=.
p={color:#000;}. To list the current working directory contents: | =. |=.
p={color:#000;}. [email protected]:~$ ls | =. |=.
p={color:#000;}. Documents code.txt ProjectDir script.sh

shortcut


=.
=.
=.
=.
=.

You can also displays the contents of specific directory without changing the current directory. Additionally, ls can be used to display information about files and directories including permissions, size, and type.

table=. =. |=.
p={color:#000;}. To display the working directory contents including extra information: | =. |=.
p={color:#000;}. [email protected]:~$ ls -lh | =. |=.
p={color:#000;}. drwxrwxr-x 2 adam adam 52.0K Nov 23 08.10 Documents

-rw-rw-r-- 1 adam adam 128 Oct 10 08.10 code.txt

drwxrwxr-x 2 adam adam 12.3M Oct 10 23.22 ProjectDir

-rwxrwx--- 1 adam adam 63 Nov 23 08.10 script.sh

-rw-rw-r-- 1 adam adam 10 Nov 23 08.10 shortcut ->

Documents | =. |=.
p={color:#000;}. To display the working directory contents including hidden files: | =. |=.
p={color:#000;}. [email protected]:~$ ls -a | =. |=.
p={color:#000;}. . .. .bash_history .bash_logout .bashrc

.cache .profile Documents code.txt ProjectDir

script.sh shortcut |

From the preceding output, the current working directory contains two directories, single-dot (.) and double-dot (..). Actually, each directory has these two directories that allow relative pathname specification. The single-dot (.) points to the directory itself. The double-dot (..) points the directory one level higher in the hierarchy (or parent of the directory).

table=. =. |=.
p={color:#000;}. To change to the parent directory using double-dot (..): | =. |=.
p={color:#000;}. [email protected]:~$ pwd | =. |=.
p={color:#000;}. /home/adam | =. |=.
p={color:#000;}. [email protected]:~$ cd ..

=.
=.

The ls command with option –F appends a special character at the end of each filename displayed to indicate the type of file.

table=. =. |=.
p={color:#000;}. To display all contents of the working directory including their type: | =. |=.
p={color:#000;}. [email protected]:~$ ls –aF | =. |=.
p={color:#000;}. ./ ../ .bash_history .bash_logout .bashrc

.cache/ .profile Documents/ code.txt ProjectDir

script.sh* shortcut@ |

To determine the file type or to guess at the type of data contained in a file you can use the file command.

=.
=.
=.
=.
=.
=.

 

table=. =. |=.
p={color:#000;}. Symbol |=.
p={color:#000;}. Descriptions | =. |=.
p={color:#000;}. @ |=.
p={color:#000;}. A linked file | =. |=.
p={color:#000;}. * |=.
p={color:#000;}. An executable file | =. |=.
p={color:#000;}. / |=.
p={color:#000;}. A subdirectory | =. |=.
p={color:#000;}. = |=.
p={color:#000;}. A socket | =. |=.
p={color:#000;}. | |=.
p={color:#000;}. A named pipe | =. |=.
p={color:#000;}. [none] |=.
p={color:#000;}. No special character appended to them and could be text files, binary data files, or special device files.

|

Table [3.1 _]6 _Symbol at the end of a filename when using ls –F

Wildcard metacharacters can simplify commands that specify more than one filename on the command line. The following are examples of how to use wildcard metacharacters together with ls command.

=.
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.

 

=.
p={color:#000;}. Descriptions
=.
=.
=.
=.
=.

Table 3.1 7 Wildcard metacharacters

3.2 Work with files and directories

The following are several useful commands to work with files and directories along with descriptions:

<>.
p<>{color:#000;}. Descriptions
<>.
<>.
<>.
<>.
<>.
<>.
<>.
<>.
<>.
<>.
<>.
<>.

Table 3.2 8 Common Linux commands to manage files and directories

To create a directory, use the mkdir command. You have to give at least one parameter to mkdir.

=.
=.
=.
=.
=.

If you decided to create a ~myfolder/backup, and there is no myfolder directory present in your home directory, you will get an error:

table=. =. |=.
p={color:#000;}. Try to create ~/myfolder/backup directory: | =. |=.
p={color:#000;}. [email protected]:~$ mkdir myfolder/backup | =. |=.
p={color:#000;}. mkdir: cannot create directory `myfolder/backup’: No such

file or directory |

When used with the -p (parents) option, intermediate or parents directories are created.

=.
=.
=.
=.
=.

A directory can be deleted with the rmdir command. When used with the -p (parents) option, all the specified directories in the path are removed.

=.
=.
=.

The rmdir command only removes empty directories.

=.
=.

To remove directories and their contents, use rm command, with the -r (recursive) and -f (force) options.

=.

Use the rm -rf commands with caution because the command-line does not have a trash container where you can restore accidentally deleted files.

One easy way to create a new empty file is with touch command.

=.

You also can use cat command to create a file. Typing the command cat followed by the output redirection operator (>) and a file name on the same line, pressing Enter to move to the next line, then typing some text and finally pressing Enter again causes the text to be written to that file.

table=. =. |=.
p={color:#000;}. To create a new file and inserting text in to it: | =. |=.
p={color:#000;}. [email protected]:~$ cat > fossfile

A free and open source software is computer program.

|

The program is terminated and the normal command prompt is restored by pressing the Ctr+D keys.

table=. =. |=.
p={color:#000;}. To view fossfile file contents: | =. |=.
p={color:#000;}. [email protected]:~$ cat fossfile | =. |=.
p={color:#000;}. A free and open source software is computer program.

|

When you no longer need a file, use rm command to remove it.

=.

As mentioned before, the command-line in general does not recover deleted files, when you use rm command to remove a file, the file is gone. Therefore, be careful when removing files. To prevent yourself from accidentally removing a file, you can use rm -i command.

=.
=.

The -i (interactive) option tells rm to prompt the user for confirmation before removing a file (and directory). When you get a prompt, type n if you want to discard the operation or type y to confirm that you want the file removed.

To copy files and directories, use the cp command. It requires two arguments at minimum: the source and the target. You can also copy one or more files to a directory by ending the cp command with a target directory. Each argument can be an absolute or relative pathname and can contain wildcards or the special metacharacters.

=.
=.
=.

If the target directory contains a file with the same name as the source file, the preceding command will overwrite the file by the new one. Use the -i option of cp to run in interactive mode, give you the opportunity to abort the operation or continue by overwriting the existing file.

=.
=.

To copy directories, use the -r option. This will cause the source directory to be recursively copied to the target directory.

=.

If the target directory exists, the source directory is copied into the target directory. Otherwise the target directory will be created with the contents of the source directory.

Much like the cp command, the mv command takes two arguments at minimum. The first argument specifies the source file or directory to be moved and the second argument specifies the target file/directory. To move several files to a destination directory, simply specify several source arguments, with the final argument on the command line serving as the target directory. The mv command works similarly to a cut-and-paste operation in which the file is copied to a new target directory and deleted from the source directory. If the target is a directory, the mv command moves the file(s) to the directory.

=.
=.
=.

If the source filename is same as an existing filename in the target directory, the mv command overwrites the target with the source. If the source is a filename of a non-existent file in the target directory, the mv command creates a new file with that filename in the target directory and moves the source file to that file. Use the -i option of mv to run in interactive mode, give you the opportunity to abort the operation or continue by overwriting the existing target.

=.
=.

Another use of the mv command is to rename files, which is simply moving a file to the same directory but with a different filename.

=.

 

3.3 Search files

To search for files or directories in the Linux directory structure is to use the find or locate command. Both of these commands can use wildcard metacharacters to do more specific searches. However, ensure that any wildcard metacharacters are enclosed within quote characters.

The find searches the directory structure recursively, starting from a certain directory for files that meet a certain criterion. You can find files by owner, size, permissions, name, modification time and more. Hence, it is slower but more versatile method for locating files on the directory tree.

<>.
p<>{color:#000;}. Descriptions
<>.
<>.
<>.
<>.
<>.
<>.

Table 3.3 9 Common find commands

When running find without arguments, the searching will be started from the current working directory.

The locate queries an index or looks in a built-in database, rather than the entire directory tree. When used without any options, locate command searches all files on the directory tree and returns too much information to display on the screen. You can use the piping to send the output to more (or less) command to make the output easier to read.

=.

This approach is really fast since it does not have to examine files and directories in real time. The disadvantage is that it is not in real time. The locate database is indexed for fast searching and it is updated automatically (usually after reboot). However, the locate command would not find files that have just been created.

=.
=.
=.

You can update the database manually by running the updatedb command. Because this modifies the system, you will need to start the command with “sudo”. The sudo command is used to run a command with administrative permissions and it will prompt you for your password.

=.
=.
=.
=.

 

3.4 View files contents

The cat command displays the entire contents of a file. If you would like to navigate the contents of a file, you can use a pager utility such as more or less. To display the top portion of a file, use the head command. The tail command allows you to display the end of a file.

The following are several useful commands to view file contents along with description:

=.
p={color:#000;}. Descriptions
=.
=.
=.
=.
=.
=.
=.

Table 3.4 10 Commands to view file contents

The more command browse through a text file. You can press the Spacebar to advance to the next page, press Enter to advance to the next line. To quit viewing the file, type q. While the less command is like more command, but allows backward movement and pattern searches.

The head and tail commands display 10 lines by default. To specify a specific number of lines to display, append -N to the command where N is the number of lines you want to display.

=.

 

 

3.5 Search files contents

We search the contents of a file for lines matching a given regular expression. Matching lines are output, non-matching lines are discarded.

Regular expressions allow you to specify a certain pattern of text within a text document. They are interpreted by a text tool program and match characters within text files on a Linux filesystem. You can use common regular expressions and extended regular expressions. Common regular expressions are available to most text tools. However, extended regular expressions are less common and available in only certain text tools.

table=. =. |=.
p={color:#000;}. Expression |=.
p={color:#000;}. Descriptions | =. |=.
p={color:#000;}. * |=.
p={color:#000;}. Matches 0 or more occurrences of the previous character | =. |=.
p={color:#000;}. .

=.
p={color:#000;}. Matches 1 character of any type
=.
=.
=.
=.

Table 3.5 11 Common regular expressions

=.
p={color:#000;}. Descriptions
=.
=.
=.
=.

Table 3.5 12 Extended regular expressions

The most common way to search for information using regular expressions is the grep command. The grep command is used to search text or searches the given file for lines containing a match to the given strings or words.

table=. =. |=.
p={color:#000;}. To display the contents of the free.txt file: | =. |=.
p={color:#000;}. [email protected]:~$ cat free.txt | =. |=.
p={color:#000;}. In Free Software Definition, a software is free software if

users have all of the following freedoms:

 

1) The freedom to run the software, for any purpose (freedom

0).

 

2) The freedom to study how the program works, and change it

to make it do what you wish (freedom 1). Access to the

source code is a precondition for this.

 

3) The freedom to redistribute copies so you can help your

neighbour (freedom 2).

 

4) The freedom to distribute copies of your modified

versions to others (freedom 3). By doing this you can give

the whole community a chance to benefit from your changes.

Access to the source code is a precondition for this.

|

Based on the contents of free.txt file, the Table 3.5-13 describes the using of the grep and egrep commands:

=.
p={color:#000;}. Descriptions
=.
=.
=.
=.
=.
=.

Table 3.5 13 Some examples of using the grep and egrep commands

 

Chapter 4


table>. >. |>/2.
p>{color:#000;}.  

|>. p={color:#000;}.  
>.

 

In this topic, you learn to control file access through appropriate use of file and directory permissions and ownerships. Each file and directory is assigned access rights or permissions for the user owner of the file, the members of a group (group owner), and everybody else (other).

 

Objective:

*
p<>{color:#000;}. Understand files ownership and permission

*
p<>{color:#000;}. Change files permissions

*
p<>{color:#000;}. Describe and set up special permissions

*
p<>{color:#000;}. Understand default permission

 

4.1 Understand files/directories permission

Each file and directory in Linux contains a set of permissions that determine who can access them and how. To view the information of ownership and permission of files or/and directories, you can use the ls –l command.

table=. =. |=.
p={color:#000;}. To view the ownership and permission of files or/and directories on your current working directory: | =. |=.
p={color:#000;}. [email protected]:~$ ls –l | =. |=.
p={color:#000;}. drwxr-xr-x 3 adam adam .. ProjectDir

-rw-rw-r-- 1 adam adam .. script.txt |

You set these permissions to limit access in one of three ways: you can restrict access to yourself alone, you can allow users in a predesignated group to have access, or you can permit anyone on your system to have access.

=.
=.
=.
=.
=.

Three different categories of users can have access to a file or directory:

*
p<>{color:#000;}. User (owner)

*
p<>{color:#000;}. Group (the members of a group)

*
p<>{color:#000;}. Others (everyone else in the system)

In the following example, the sample.txt file is owned by the user adam (user owner) and belongs to the group devgrp:

table=. =. |=.
p={color:#000;}. -rw-rw-r-- 1 adam devgrp 168 May 11 11:55 sample.txt |

When a user creates a file or directory, that user’s name or the username and primary group become the user owner and group owner of the file, respectively.

=.
=.
=.
=.

Only the root user can change ownership of a file or directory. To change the ownership of a file or directory, you can use the chown (change owner) command, which takes two arguments at minimum: the new owner and the files or directories to change.

=.
=.
=.
=.

You can also change group ownerships recursively throughout the directory tree using the –R option to the chown command.

=.

 

table=. =. |=.
p={color:#000;}. Then, view the permissions of the directory ProjectDir and its contents: | =. |=.
p={color:#000;}. [email protected]:~$ ls –l | =. |=.
p={color:#000;}. -rw-rw-r-- 1 idris adam .. code.txt

drwxr-xr-x 3 idris adam .. ProjectDir

-rw-rw-r-- 1 adam adam .. script.txt | =. |=.
p={color:#000;}. [email protected]:~$ ls –l ProjectDir | =. |=.
p={color:#000;}. -rw-rw-r-- 1 idris adam .. mon.txt

-rw-rw-r-- 1 idris adam .. tue.txt

-rw-rw-r-- 1 idris adam .. wed.txt |

You can use the chgrp (change group) command to change the group owner of a file or directory. The chgrp command takes two arguments at minimum: the new group owner and the files or directories to change.

table=. =. |=.
p={color:#000;}. To change the group owner of code.txt to the devgrp[_:_] | =. |=.
p={color:#000;}. [email protected]:~$ sudo chgrp devgrp code.txt | =. |=.
p={color:#000;}. To view the ownership of your current directory contents: | =. |=.
p={color:#000;}. [email protected]:~$ ls –l | =. |=.
p={color:#000;}. -rw-rw-r-- 1 idris devgrp .. code.txt

drwxr-xr-x 3 idris adam .. ProjectDir

-rw-rw-r-- 1 adam adam .. script.txt |

The chgrp command also accepts the –R option to change group ownership recursively throughout the directory tree.

=.

 

table=. =. |=.
p={color:#000;}. To view the ownership of the directory ProjectDir and its contents: | =. |=.
p={color:#000;}. [email protected]:~$ ls –l | =. |=.
p={color:#000;}. -rw-rw-r-- 1 idris devgrp .. code.txt

drwxr-xr-x 3 idris devgrp .. ProjectDir

-rw-rw-r-- 1 adam adam .. script.txt | =. |=.
p={color:#000;}. [email protected]:~$ ls –l ProjectDir | =. |=.
p={color:#000;}. -rw-rw-r-- 1 idris devgrp .. mon.txt

-rw-rw-r-- 1 idris devgrp .. tue.txt

-rw-rw-r-- 1 idris devgrp .. wed.txt |

You can change both the user owner and the group owner at the same time using the chown command.

table=. =. |=.
p={color:#000;}. To change the user and group owner of script.txt[_:_] | =. |=.
p={color:#000;}. [email protected]:~$ sudo chmod idris.devgrp script.txt | =. |=.
p={color:#000;}. To view the ownership of your current directory contents: | =. |=.
p={color:#000;}. [email protected]:~$ ls –l | =. |=.
p={color:#000;}. -rw-rw-r-- 1 idris devgrp .. code.txt

drwxr-xr-x 3 idris devgrp .. ProjectDir

-rw-rw-r-- 1 idris devgrp .. script.txt |

Note that there must be no spaces before and after the “. character in the chown commands shown in the preceding output. You can also use the “: character instead of the “. character in the chown command to change both the user and group ownership.

 

4.2 Change files permissions

 

Every file and directory in Linux contains information regarding permissions in its mode. The mode of a file is divided into three sections based on categories or the user(s) who receive(s) the permissions to that file or directory:

*
p<>{color:#000;}. User (owner) permissions

*
p<>{color:#000;}. Group (group owner) permissions

*
p<>{color:#000;}. Others (everyone else in the system) permissions

Each category has its own set of regular permissions; read, write and execute.

In the following example, the first set of characters on the left is a list of the permission set for the sample.txt file:

table=. =. |=.
p={color:#000;}. -rw-rw-r-- 1 adam devgrp 168 May 11 11:55 sample.txt |

The first character indicates the type of file. The preceding example is a file because the first character is a dash (-). If the first character is d, information about a directory is being displayed.

The next nine characters are arranged according to the different ownerships. The first set of three characters is the owner’s set of permissions for the file. The second set of three characters is the group owner’s set of permissions for the file. The last set of three characters is the other users’ set of permissions for the file.

An empty permission is represented by a dash. The read permission is represented by r, write by w and execute by x. Permissions for files are interpreted differently from those for directories. Also, if a user has a certain permission on a directory, that user does not have the same permission for all files or subdirectories within that directory; file and directory permissions are treated separately by the Linux system. Table 4.2-14 shows a summary of the different permissions and their definitions.

=.
p={color:#000;}. Definition for files
=.
p={color:#000;}. Definition for directories
=.
=.
=.

Table 4.2 14 Linux permissions

Only the owner and the root user can change permission of a file or directory. To change the ownership of a file or directory, you can use the chmod (change mode) command. You can use the chmod command to change file’s mode with two methods: symbolic method and absolute method.

The symbolic method of setting permissions uses the character r, w and x for read, write and execute, respectively. Any of these permission can be added or removed. The symbol to add a permission is the plus sign, +. The symbol to remove a permission is the minus sign (-). Table 4.2-15 shows a list of options or symbols for setting permission with the chmod command.

=.
=.

 

=.
p={color:#000;}. Descriptions
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.
=.

Table 4.2 15 The chmod options for setting permissions.

=.
=.
=.
=.
=.
=.
=.

The absolute method changes all the permissions at once, instead of specifying one or the other. The three categories, each with three permissions, conform to an octal binary format. The first octal digit applies to the owner category, the second to the group owner and the third to the others category.

Each octal digit determines the read, write and execute permissions for its category. Use 4 (22) for read permission, 2 (21) for write and 1 (20) for execute. The read, write, execute permission is simply the addition of 4+2+1 to get 7.

Figure 4.2 10 Numeric representation of the mode

To represent the mode rw-r—r—, you can use the numbers 644 because user owner has read and write (4 + 2 = 6), group owner has read (4), and others has read (4). The mode rwxr-x—- can be represented by 750 because user owner has read, write, and execute (4 + 2 + 1 = 7), group has read and execute (4 + 1 = 5), and others has nothing (0).

=.
=.
=.
=.
=.
=.
=.

 

4.3 Describe and set up special permissions

 

You can use three special permissions on files and directories:

*
p<>{color:#000;}. SUID (Set User ID) permission

*
p<>{color:#000;}. GUID (Set Group ID) permission

*
p<>{color:#000;}. Sticky bit permission

Table 4.3-16 shows a summary of the different special permissions and their functions on files and/or directories.

table=. =. |=.
p={color:#000;}. Permission |=.
p={color:#000;}. Function for files |=.
p={color:#000;}. Function for directories | =. |=.
p={color:#000;}. SUID (Set User ID |=.
p={color:#000;}. Allows a user to execute a binary compiled program and become the owner of the file for the duration of execution.

|=. p={color:#000;}. No special function | =. |=. p={color:#000;}. GUID (Set Group ID) |=. p={color:#000;}. Allows a user to execute a binary compiled program and become the member of group that is attached (group owner) to the file for the duration of execution. |=. p={color:#000;}. If a user has a write permission and then creates new files or subdirectories, the user’s name become the owner of the file and directory’s group become the group owner of the files or subdirectories. | =. |=. p={color:#000;}. Sticky bit |=. p={color:#000;}. No special function |=. p={color:#000;}. The contents of the directory (files and directories) can only be deleted or re-named by the root user or the owner of the files or directories. |

Table 4.3 16 Linux special permissions

The mode of a file or directory does not have a section for special permissions. These special permissions will mask the execute permission because they require execute permission to perform their function. If the special permissions are set on a file or directory without execute permissions, then the ineffective special permissions are capitalized as in in .

Figure 4.3 11 Representing special permissions in the mode

 

Figure 4.3 12 Representing ineffective special permissions in the mode

In the following example, the code.txt file is set with SUID dan GUID permissions using symbolic method with chmod command:

=.
=.
=.

The following example sets the sticky bit to the code.txt file using chmod command, with symbolic method:

=.
=.
=.

 

The octal digit for SUID is 4, GUID is 2 and sticky bit is 1.

Figure 4.3 13 Numeric representation of regular and special permissions

 

=.
=.
=.
=.
=.
=.
=.

 

 

4.4 Understand default permissions

New files are given rw-rw-rw- and new directories are given rwxrwxrwx by the system when they are created. Then, the umask (user mask) takes away permissions on new files and directories immediately after they are created. To verify the current value of umask, use the umask command with no arguments and note the final three digits in the output.

=.
=.

From the preceding output, the umask is 002, which specifies that nothing (0) is taken away from the user, also nothing (0) is taken away from members of the group and write permission (2) is taken away from others on new files and directories when they are first created and given permissions by the system. An example of how an umask of 002 can be used to alter the permissions of a new file or directory after creation is shown in .

Figure 4.4 14 Performing a umask 002 calculation

To change the current umask, you can specify the new umask value as an argument to the umask command.

>.
>.
>.

 

 

About the Author

Sudiman Suhaili is the author of the ‘Work with the Command-line: To manage files and directories in Ubuntu’. The book is aimed at anybody, especially at Polytechnic students who are looking to deepen their understanding of the command-line in Linux. It provides the essential skills in Linux operating system administration. It has been published in Malaysia in 2017.

 

His professional experience includes more than 11 years in education, especially in TVET (Technical/Vocational Education and Training) and management level in the academic leadership, management and assessment, for the Information Technology programme.

 

 

 

 

 

Connect with Sudiman Suhaili

I really appreciate you reading my book! Here are my social media coordinates:

 

Friend me on Facebook: https://www.facebook.com/sudiman.suhaili

Follow me on Twitter: https://twitter.com/sudiman_suhaili

Follow me on Instagram: https://www.instagram.com/sudiman_suhaili

Favorite my Shakespir author page: https://www.Shakespir.com/profile/view/sudiman

 


Work with the Command-line: To manage files and directories in Ubuntu

This book is aimed at anybody who are looking to deepen their understanding of the command-line in Linux, the essential skills to use and manage the operating system. This book also an ideal reference for beginners to learn the common and basic Linux commands but it is also great for intermediate users. In this book, we use the Ubuntu to understand how Linux can be used, explore the Linux directory tree and work on the command-line to perform various tasks related to manage files and directories in the system. Most of the examples in this book are accomplished in the Ubuntu LTS. However, all the commands in this book are generally can be applied in most Linux distributions.

  • ISBN: 9789671417874
  • Author: sudiman
  • Published: 2017-06-19 02:50:20
  • Words: 10146
Work with the Command-line: To manage files and directories in Ubuntu Work with the Command-line: To manage files and directories in Ubuntu