You are on page 1of 92

The Linux Operating System

Learning objective
After completing this topic, you should be able to identify the basic characteristics of the Linux operating system.

1. Introduction to Linux
Linux was developed to run on IBM-based hardware. It is cheaper than UNIX, is platform independent, and is readily available for almost every type of hardware, including Pentium-class CPUs. GNU's Not UNIX (GNU) is a software system developed by the Free Software Foundation (FSF), an organization that promotes and distributes open source software. The GNU Project was launched to help create non-proprietary software and resulted in the General Public License (GPL). GPL is a license that states that anyone can download, modify, and redistribute software. It is also referred to as a copyleft, which means that no one can limit the redistribution of modified software. Linux is an open source operating system (OS) released under the GPL. The benefits of using Linux include

multiuser environments multitasking speed stability extensive software availability extensive hardware support

multiuser environments Multiple users can log on to the Linux operating system, and execute multiple processes simultaneously. multitasking Linux systems can run many applications at the same time. speed Linux is faster than many commercial operating systems. It is optimized to make efficient use of its hardware resources, which enables it to run with very little overhead while delivering outstanding performance.

stability Linux is very stable because of its design and modularity. If an application crashes, the entire system is not affected. Also, if you install new applications, or modify settings, you don't need to restart the system. This improves uptime. extensive software availability Linux software is freely available. In addition to the main operating system, many CDs' worth of other software are also bundled with Linux distributions. extensive hardware support Linux is independent of the platform on which you run it, so it can run on many different platforms new and old, for example

Digital/Compaq (now HP) Alpha SUN SPARC Motorola 68000 PowerPC Intel x86

In addition to system benefits, an advantage of Linux is that errors in the source code are identified and fixed more quickly than in proprietary operating systems because it's an opensource operating system.

Question
What are the benefits of using Linux? Options: 1. 2. 3. 4. Multiuser support Stability Support for multitasking Windows application support

Answer
Linux supports multiuser environments and multitasking, and provides a high degree of stability. Option 1 is correct. Linux enables multiple users to log in to the operating system, and to execute multiple processes simultaneously. Option 2 is correct. Linux is very stable. If one application fails, it doesn't affect the entire system. Option 3 is correct. Linux can run many applications at the same time. Option 4 is incorrect. Although many Linux versions of Windows applications exist, Windows applications will not work directly under Linux.

2. Components of the Linux architecture


A kernel is the fundamental component of the Linux operating system. It contains hardware drivers for the devices installed on the system. The kernel is the part of the system that loads first, and it stays in memory. A monolithic kernel is set up so that all drivers are compiled in the kernel. There's no need for the user to load any modules. However, when you install new drivers, you need to recompile the kernel. As a result, the kernel becomes larger and slower, and requires more memory. A modular kernel is set up so that most hardware drivers are compiled as modules. As a result, you don't have to recompile the kernel when installing new hardware devices. In practice, kernels are a combination of monolithic and modular where some drivers are compiled into the kernel and some are compiled as modules. The Linux kernel acts as a mediator between the system's hardware and software. It is also responsible for memory management and multiplexing it divides a CPU's processing capacity between applications so that they can run simultaneously. The Linux architecture consists of a

kernel space user space

kernel space The kernel space contains and runs the kernel and device drivers. It maintains system processes to keep them stable. Kernel code cannot directly access or write to the user space. user space The user space manages user processes, such as e-mail, running on a system. Together with the kernel, these processes control functions such as printing to the screen. A user process cannot directly access the kernel space.

Question
Which part of the Linux architecture handles communication between the operating system and an external device? Options: 1. Kernel space 2. Modules 3. User space

Answer
The kernel space handles communication between the operating system and an external device. Option 1 is correct. The kernel contains drivers for the hardware devices installed on the system, and acts as a mediator between the system's hardware, including external devices, and the operating system software. Option 2 is incorrect. The Linux kernel can be modular. However, the kernel, rather than separate modules, controls the interaction between the Linux operating system and hardware devices. Option 3 is incorrect. The user space manages user processes running on a system. The principal interface between users and the internal workings of a Linux system is either a graphical user interface (GUI) or a shell. An X Window System is an application that runs on top of the base operating system to enable Linux to support a GUI. A GUI is a user interface that uses graphics such as icons, menus, and pictures to enable a user to interact with a system. K Desktop Environment (KDE) and GNU Network Object Model Environment (GNOME) are popular Linux GUIs. A shell is a program that acts as an interface between a user and an operating system, without using a graphic display. It reads and executes commands entered at the command line. The default shell is the Bourne Again shell (bash). Other shell types are the Bourne shell (sh), C shell (csh), and Korn shell (ksh).

Question
Which user interfaces for Linux are GUIs? Options: 1. 2. 3. 4. bash GNOME KDE ksh

Answer
GNOME and KDE are GUIs for Linux.

Option 1 is incorrect. The bash shell is the default Linux shell, which executes commands entered by users at the command line rather than providing a graphical interface. Option 2 is correct. GNOME is a popular GUI for Linux. It enables users to interact with the operating system using graphics such as icons and menus. Option 3 is correct. KDE is a GUI that enables users to interact with a system using icons, menus, and other graphical features. Option 4 is incorrect. The ksh shell is a Linux shell that provides a command-line interface between users and the operating system.

Summary
Linux is a freely available, open- source operating system released under the GNU General Public License (GPL). It is cheaper than UNIX, and is independent of the platform you run it on. It supports multiuser environments, is fast and stable, and provides extensive hardware and software support. The kernel is the basic component of the Linux architecture. It is a combination of modular and monolithic kernel types and is responsible for memory and task management . The Linux user space manages user processes. Users can interact with a Linux system using either a graphical user interface (GUI) or a shell.

Table of Contents
| Print | Contents |

Why use the Linux shell?


Abstract
This article discusses the advantages of using a Linux shell rather than a graphical user interface (GUI).

Introduction
Most PC users communicate with the operating system on their machines using a graphical user interface (GUI), such as those used in Microsoft Windows XP/Vista or Mac OS X. Linux has its own GUIs, most notably GNU Network Object Model Environment (GNOME) and the K Desktop Environment (KDE). GUIs provide buttons, menus, icons, and all the other point-andclick features that have simplified modern computing so greatly. However, it is a mistake to assume that GUIs are always the best way to communicate with an operating system. Although

GUIs certainly provide simplicity, they tend to obscure some of a computer's capabilities from the user. This is where a shell comes in.

Advantages of using a shell


Greater control
A shell is a program that acts as an interface between the user and the operating system, just as a GUI does. However, a shell works without graphics when you use one, you issue instructions to the operating system by typing in commands. In fact, the shell is often referred to as a command interpreter. This may seem like a return to basic computing, but a command-line interface lets you exercise a degree of control over the operating system that would otherwise be lacking. There are a number of reasons for this:

with a GUI, only the options provided by the interface are available to the user lack of space on a screen can limit the number of options that a GUI displays no standard methods exist within GUIs for performing standard command-line tasks, such as linking commands in sequences, redirecting output from one destination to another, or collecting commands into scripts

A disadvantage of using a command-line interface is that the user needs to learn a wide variety of sometimes cryptic commands and their associated options. However, the commands are more powerful and adaptable than their GUI counterparts, because they can be extended and finetuned through the use of options. An expert user of a command-line interface can issue complex commands very quickly. Techniques also exist to link multiple commands together with pipes and redirections, so that the output of one command becomes the input of another. Linux can interpret commands issued using the shell more quickly than GUI commands. This is because shell commands are nothing more than simple ASCII text. Some shells even enable you to define your own commands.

Automation of common tasks


A shell has another advantage over a GUI in that it keeps a history list of recently issued commands. This enables a user to step back and forth through this list, reusing commands at any point. In addition, a shell enables you to string commands together to form a shell script. These scripts work in a similar way to batch files, issuing multiple commands as one. You can use them to automate common tasks that would otherwise require you to issue several, consecutive commands.

Speed and efficiency


In hardware terms, a shell is a more attractive proposition than a GUI. Shells are much less resource-intensive than GUIs they require less memory, for example. This means that a

command issued in the shell will run more quickly and efficiently than the same command run in a GUI. It also means that a shell supports Linux's multitasking environment, in which multiple tasks run simultaneously, more comfortably than a GUI, in which the GUI itself competes for CPU resources.

Shell evolution
Since its creation as a derivative of UNIX, Linux has given rise to a number of shells, which have evolved along with the operating system itself. When a new shell is developed, it doesn't spell the end for all previous shells. Many different Linux shells are available, and each has particular strengths. The one you use depends on your own preferences and on the task you wish to undertake. The default shell in most Linux installations is the Bourne Again shell, or /bin/bash. It is a successor to the Bourne shell, or /bin/sh, which was an early and less powerful Linux shell. The Bourne Again shell was created and is distributed by the Free Software Foundation. It offers features such as command-line editing and filename completion. It is an ideal first shell for Linux newcomers. In addition, bash supports the syntax used by another Linux shell called the C shell, or /bin/csh, which increases its flexibility. You can find out which shell you're running at any time by typing the command echo $SHELL at the shell prompt. The default shell is specified in the /etc/passwd file and can be changed there for each user.

Summary
A Linux shell, or command interpreter, is more flexible and more powerful than a graphical user interface (GUI). It offers users more control by enabling them to issue commands directly via the command line. Users can extend and fine-tune existing commands, or design new commands to perform specific tasks. In addition, users can recall shell commands and link them in files to form shell scripts, which can automate common tasks. Linux commands use a simple ASCII format, and a shell has lower resource requirements than a GUI. This enables a computer to process instructions to the Linux operating system faster and more efficiently from a shell than from a GUI. Several different Linux shells, each with particular strengths, are available. The Bourne Again shell, or bash, is the default shell on most Linux machines.

Table of Contents
| Introduction | | Advantages of using a shell | | Shell evolution |

Copyright 2008 SkillSoft. All rights reserved. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries.

The Linux Shell Prompt


Learning objective
After completing this topic, you should be able to use shell commands to verify the environment, find information about commands, use shortcuts, and support multitasking.

1. Characteristics of the bash shell


You perform tasks in Linux by issuing commands in a shell. A shell is a program that mediates between the user and the operating system. When you type in a command, the shell interprets it and passes it to the kernel, or operating system, for processing. You can choose to enter commands in a number of shells, including the Bourne shell (sh), the C shell (csh), and a version of the Korn shell (pdksh). However, the Bourne Again shell (bash) is the default in most Linux distributions. Each shell uses a prompt a character that the shell uses to indicate that it's ready to receive input. The bash, Korn, and newer C shells use a dollar sign ($) by default, whereas older versions of the C shell use the percent symbol (%). The only other shell prompt you're likely to see is the hash character (#), which indicates that you're logged in as root. This symbol is common to all shells. The bash shell is an updated version of the Bourne shell, which was the first UNIX shell. It was written by Steve Bourne and John Mashey, who developed the shell while working at AT&T Bell Laboratories. The bash shell features 48 built-in commands and 12 command-line options. These enhance the functionality of the Bourne shell and combine its features with other capabilities, such as command editing, command history, and command completion.

Question
Suppose that you've logged in to a shell as a regular user. What character does the bash shell use to indicate that it's ready to receive input?

Options: 1. Dollar sign ($) 2. Hash character (#) 3. Percentage symbol (%)

Answer
The bash shell uses a dollar sign ($) by default to indicate that it's ready to receive input from a regular user. Option 1 is correct. The bash shell and the Korn shell use a dollar sign ($) as a prompt by default for a regular user. Option 2 is incorrect. A hash character (#) is the default prompt on all shells for the root user. Option 3 is incorrect. Older versions of the C shell use the percent symbol (%) as a prompt.

2. Basic command structures


You enter commands in the shell by typing a command or instruction at the command-line prompt. Command-line instructions consist of commands and usually one or more arguments. An argument is an option you enter after a command to provide the shell with additional information about what the command must do. Arguments can be categorized as required, implied, or optional. The shell starts to interpret command-line instructions once you press the Enter key. Then it passes the command to the kernel for processing. Results known as output can then be transferred from the kernel back to the shell, where they are visible on the terminal screen. If there are a number of shells at your disposal, you may sometimes need to verify which shell you are using. To do this, you check the value of the environment variable named SHELL. Even if you change the shell in the middle of a session, the SHELL environment variable will not change.

Note

Environment variables are responsible for the look and function of a shell. They act as containers that store information about the shell, such as the home directory, the logged-on user's username, and the history file. Examples of environment variables include SHELL, which identifies the shell you are using, and PS1 which defines your shell prompt. Suppose that you're Miguel Alvarez and you work for a travel company called Easy Nomad. You can verify which shell you are using by issuing the command
echo $SHELL [malvarez@easynomad1]$ echo $SHELL

The echo command causes whatever follows it to be printed to the terminal screen.
[malvarez@easynomad1]$ echo $SHELL

By placing a dollar sign ($) in front of the SHELL variable, you ensure that the contents of the SHELL variable rather than the word "SHELL" are printed to the screen.
[malvarez@easynomad1]$ echo $SHELL /bin/bash [malvarez@easynomad1]$

When you enter the echo $SHELL command, its output verifies that you are using the bash shell. If the C shell is your login shell and you wish to change to the bash shell, you use the chsh command with this syntax to change permanently to a different shell.
[malvarez@easynomad1 ~] $ chsh -s /bin/bash

chsh -s shell [username]

Note
You need to specify a username only if you are the root user and you are changing the shell for another user. If no username is entered, the change of shell will apply only to the user who is currently logged on. In the chsh command, the -s option indicates that you wish to specify a new shell, and /bin/bash is the full path to the shell you wish to change to. If you are not logged in as the root user, the chsh command requires a password before it can take effect.
[malvarez@easynomad1 ~] $ chsh -s /bin/bash Changing shell for malvarez. Password:

Shell changed. [malvarez@easynomad1 ~] $

Note
When using the chsh command, you need to log out and back in again in order for the SHELL environment variable to change. Alternatively, you can switch to the bash shell temporarily by simply entering /bin/bash the full path to the shell in the root directory at the prompt. This change will last only for the current session.
[malvarez@easynomad1 ~] $ /bin/bash [malvarez@easynomad1] $

You will remain in the bash shell until you enter the command
exit [malvarez@easynomad1 ~] $ /bin/bash [malvarez@easynomad1] $ exit exit [malvarez@easynomad1 ~] $

This returns you to the parent shell.

Question
Suppose that you're logged into a shell as a regular user, but you're not entirely certain which shell you're using. Which of these commands returns the name of the shell you're using? Options: 1. 2. 3. 4.
$SHELL echo $SHELL echo $shell echo SHELL

Answer
You type echo $SHELL to view the name of the shell you're using. Option 1 is incorrect. This is the correct way to reference the SHELL variable, but you need to include the echo command to print output to the screen.

Option 2 is correct. The echo command outputs text to the screen, and the $ in front of the SHELL variable means that the value of the variable, rather than the word "SHELL", is returned. Option 3 is incorrect. This is the correct form, but Linux is case sensitive, so SHELL needs to be in uppercase. Option 4 is incorrect. Although you do use the echo command to print output, you need a dollar sign ($) in front of the SHELL variable to return its value, rather than the word "SHELL".

3. The info, help, and man commands


Linux has a vast array of built-in and system commands. For this reason, three useful commands info, help, and man enable you to check the functions of commands and the options you can use with them. Each of these commands provides information about Linux commands in a different way:
help help info man

The help command displays a list of built-in commands for the shell. To access additional information about any listed commands, you use this syntax: help command
info

The info command displays online hypertext command documentation, which is arranged hierarchically by topic. To retrieve general information about a command, you use the syntax info command
man

The man command provides information on system commands. To get details for a specific command, you use the syntax man command Suppose that you need information about the echo command. You enter info echo.

The command output describes the function of the echo command and of the options you can use with it.

Supplement
Selecting the link title opens the resource in a new browser window. Code window View the output of the info echo command. Suppose that you want help in using the echo command. You enter help echo. The command output describes the format of output from the echo command, as well as the options you can use with the command. Suppose you want comprehensive information about the echo command. You enter man echo. The output identifies the echo command , explains its function and options, and directs you to full documentation for the command.

Supplement
Selecting the link title opens the resource in a new browser window. Code window View the full output of the man echo command. If you are unsure of a command name, you can use the following syntax to locate a specific command: man -k searchterm
[malvarez@easynomad1] $ man -k echo

In response, the shell displays a list of all the commands that include the search term in their description.

Question
Suppose that you want to see a list of commands that include the search term "echo".

Which of these commands will achieve this? Options: 1. 2. 3. 4.


help k echo info echo info k echo man k echo

Answer
You enter man k echo to view a list of commands that include the search term "echo". Option 1 is incorrect. The help command provides help with commands, but doesn't support searches. Option 2 is incorrect. The info command provides information about commands, but doesn't support searches. Option 3 is incorrect. The info command doesn't support the -k option, which enables a command to use a search feature. Option 4 is correct. The man command has a search feature, which you activate using the -k option. The man -k command is the same as the apropos command.

4. Using shortcuts and multitasking


Linux commands are categorized as either built-in or system commands. Built-in commands run as subroutines of the shell program itself. They are specific to a particular shell, but most shells contain similar commands. Built-in commands for the bash shell include echo, exit, and history. System commands are programs that exist as standalone files. When a user enters a system command or file name, the shell searches through the user's directory path until it finds the file that contains the specified program. Permissions determine which commands users can access. It is important to prevent the system commands from being overwritten. Consequently, you should grant only "read" and "execute" permissions even to experienced users for these commands. The shell provides shortcuts for entering commands by enabling you to

edit command lines

enter only the first few characters of file and directory names enter more than one command on a line repeat previous commands use the output of one command as an argument of another use variables in commands

edit command lines If you make an error when entering a command, you can repeat the command with a substitution by using a caret (^) in the syntax ^oldtext^newtext. The command, with the correct text in place, is then echoed to the terminal screen. enter only the first few characters of file and directory names You can enter just the first few characters of a file or directory name to identify it uniquely, and then press the Tab key to have the shell fill in the rest of the characters. enter more than one command on a line You can enter multiple commands on a line by separating each one with a semicolon (;). repeat previous commands You can repeat the last command you entered by typing two exclamation marks (!!). Alternatively, you can type !co, for example, to repeat a previous command beginning with the characters "co". use the output of one command as an argument of another You can enclose a command in backquotes (`) to use it as an argument to another command. The backquoted command will be executed first, and its output passed to the first command as an argument. To do this, you use the syntax command1 `command2` use variables in commands You can use variables, such as SHELL, HOME, or PATH, in commands to modify their default behavior. A common use is to echo, or print out, the contents of a variable to your terminal screen. A key attribute of Linux is its multitasking functionality. This means that it can perform a number of commands at the same time. For this to happen, Linux assigns commands to the foreground or background. The command executing at the command line is the only job that can be in the foreground. However, you can run many jobs in the background simultaneously, because they do not tie up the system. You can send a job directly to the background by entering an ampersand (&) at the end of the command. A job number, designed to monitor the status of a command, is assigned to each command as it is sent to the background. The first command is 1, the second is 2, and so on.

You can send a command to the background while it is running by performing two steps. First, you use Ctrl+Z to suspend the job. Then you type bg to move the job to the background, where it resumes execution. You can bring a background job to the foreground by typing this command fg jobnumber Alternatively, you can cancel a job running in the background by typing the command kill %jobnumber

Question
Which character do you use to sequence commands together on a single line? Options: 1. Ampersand (&) 2. Exclamation mark (!) 3. Semicolon (;)

Answer
You use the semicolon (;) character to sequence commands together on a single line. Option 1 is incorrect. You use an ampersand (&) character at the end of a command to run it in the background. Option 2 is incorrect. You use the exclamation mark (!) character in a conditional execution statement, rather than to chain commands. Option 3 is correct. The semicolon (;) character enables you to chain multiple commands, so that they execute in sequence when you press Enter.

Question
Identify the commands or characters you use to run a command in the background. Options: 1. Ampersand (&) 2. bg 3. Dollar sign ($)

4. fg 5. kill

Answer
You can run a command in the background either by adding an ampersand (&) character after it, or by entering the bg command after stopping it by using Ctrl+Z. Option 1 is correct. You can run a command in the background by appending an ampersand (&) to it. Option 2 is correct. After stopping a command using Ctrl+Z, you can push it to the background using the bg command. Option 3 is incorrect. The dollar sign ($) character is for accessing the values of variables. Option 4 is incorrect. You use the fg command to bring a command to the foreground. Option 5 is incorrect. The kill command terminates a running process.

Summary
Linux operates through shells that interpret commands. Users can choose from a number of shells, but the Bourne Again shell, or bash shell, is the standard in most Linux distributions. Command-line instructions generally consist of commands and arguments. You can use commands to check which shell you are using and to change to another shell, if necessary. Users can use the info, help, and man commands to help them use the range of available commands. The man command supports a search feature that you can call using the -k option. Linux has a vast array of commands, which are categorized as either built-in or system commands. The shell enables users to take shortcuts, such as entering multiple instructions on one line or repeating previous instructions, when they are issuing commands.

Table of Contents
| Print | Contents | Close |

Basic Linux Commands


Learning objective

After completing this topic, you should be able to issue basic shell commands to handle directory and file information.

1. Directory-specific commands
In Linux, a directory is a file that serves as a container for other files. It can also contain subdirectories, which can in turn contain their own files and subdirectories. You can issue commands in the shell to manipulate the location and contents of a directory. Commands for manipulating directories include
pwd pwd ls cd mkdir rmdir

The pwd command enables you to check which directory you are currently working in.
ls

The ls command enables you to list directory contents.


cd

The cd command enables you to change the directory in which you are currently working. To change from one directory to another, you use the syntax cd directory.
mkdir

The mkdir command enables you to create a directory.


rmdir

The rmdir command enables you to delete a directory using the syntax rmdir directory. It's important to note that this command will delete an empty directory only. You can use the rmdir command with the -p option to remove a full directory hierarchy. The ls command supports specific options that enable you to specify how it lists directory contents. Options for the ls command include
-a -A -c -d -l -r

-a

The -a option lists all files including hidden files, whose names begin with a period in the working directory.
-A

The -A option lists all files including the normally hidden files, whose names begin with a period but does not list the implied . and .. directories.
-c

The -c option sorts files by their status change time, beginning with the most recent file.
-d

The -d option reports only on a directory, and not on its contents.


-l

The -l option provides a list of files in long format, showing user permissions and other details.
-r

The -r option lists files in the current directory in reverse order.

Question
Suppose that you want to view a list of files sorted by status change time. Which command do you enter to do this? Options: 1. 2. 3. 4.
ls ls ls ls -a -c d -r

Answer
You type ls -c to list files by status change time rather than their creation or modification time. Option 1 is incorrect. Using the -a option with the ls command lists all files, including hidden files, in the working directory. Option 2 is correct. Using the -c option with the ls command sorts files by their status change time, beginning with the most recent file. Option 3 is incorrect. Using the -d option with the ls command lists subdirectories in the directory only. Option 4 is incorrect. Using the -r option with the ls command lists all files in the current directory in reverse order. You can combine ls options. For example, to view a list of all files and a long-format list, you can combine ls with -l and -a in this command

ls -la [malvarez@easynomad1]$ ls -la

The output of the command lists each file, as well as long-format details about it.
total 68 drwxr-xr-x drwxr-xr-x -rw-r--r-drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x dr-xr-xr-x drwx-----drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxrwxrwt drwxr-xr-x drwxr-xr-x 20 20 1 2 3 1 65 7 2 12 2 7 2 87 12 2 2 9 16 13 20 root root root root root root root root root root root root root root root root root root root root root root root root root root root root root root root root root root root root root root root root root root 4096 4096 0 4096 4096 0 4096 4096 4096 4096 4096 4096 4096 0 4096 4096 4096 0 4096 4096 4096 May May May May May Dec May May May May Feb May Jan May May May Feb May May May May 26 26 26 18 26 31 26 24 18 18 2 25 5 26 26 18 2 26 26 18 20 06:44 06:44 06:44 02:40 06:44 1969 11:18 10:15 07:37 02:52 12:10 11:46 05:47 02:43 06:47 07:31 12:10 02:43 11:31 02:40 07:10 ./ ../ .autofsck bin/ boot/ dev/ etc/ home/ initrd/ lib/ media/ mnt/ opt/ proc/ root/ sbin/ srv/ sys/ tmp/ usr/ var/

To check which files are contained in another directory, you need to enter its path as an argument for the ls command. So to get a listing of files in the /usr/sbin directory, for instance, you enter the command
ls /usr/sbin [malvarez@easynomad1]$ ls /usr/sbin

The names of the files contained in the /usr/sbin directory then display.

Supplement
Selecting the link title opens the resource in a new browser window. Launch window View the complete output of the ls /usr/bin command. The cd command enables you to switch directories by specifying either a relative or an absolute pathname to the new directory.

An absolute path specifies the exact location of a directory in relation to the root directory. A relative path identifies the location of a directory in relation to the current directory, and uses pseudonyms to identify the current and parent directories.
[malvarez@easynomad1]$ cd

Navigating by relative pathnames is sometimes quicker and easier than typing the full path or navigating in multiple steps. Suppose that your present working directory i /home/malvarez. To switch from this directory to the "Documents" subdirectory using an absolute pathname, you enter this cd command.
[malvarez@easynomad1]$ cd /home/malvarez/Documents

The initial forward slash (/) represents the root directory within which all files and directories are stored and further forward slashes indicate subdirectories. To switch from the directory /home/malvarez/documents/ to the /home/malvarez/Pictures subdirectories using a relative pathname, you can enter the command
cd ../Pictures [malvarez@easynomad1]$ cd ../Pictures

Each dot in the command represents a parent directory. In this example, the pair of dots represents the directory /home/malvarez/.

Question
Match the characteristics to the types of pathnames. Options: 1. 2. 3. 4. Employs pseudonyms to indicate current and parent directories Includes an explicit reference to the root directory Specifies the exact location of a file Specifies the location of a file in relation to the current working directory

Targets: 1. 2. 3. 4. Absolute Relative Absolute Relative

Answer

An absolute path specifies the exact location of a file or directory in the filesystem and makes explicit reference to the root directory. A relative path identifies the location of a file or directory in relation to the current directory, and uses pseudonyms to identify the current and parent directories. Suppose that you're Miguel Alvarez, a systems administrator at Easy Nomad. You want to create a new directory called "revenues", and a separate subdirectory in "revenues" for each month of the year. Before beginning to do this, you check which directory you are currently working in. You enter pwd. The pwd command displays the name of the present working directory in this case, the root directory (/) on the terminal screen. Once you have your bearings in the directory hierarchy, you can ensure that the commands you issue are accurate.
[malvarez@easynomad1]$ pwd / [malvarez@easynomad1]$

You decide to list the files contained in your working directory, to check for content you want to place in the new directory you create. You enter ls. The names of all the files in the current directory display.
[malvarez@easynomad1]$ pwd / [malvarez@easynomad1]$ ls bin/ dev/ home/ lib/ mnt/ proc/ sbin/ usr/ boot/ etc/ initrd/ media/ opt/ root/ srv/ tmp/

var/

To create a directory called "revenues" in the /home/malvarez directory, you enter the command
mkdir ~/revenues [malvarez@easynomad1]$ pwd / [malvarez@easynomad1]$ ls bin/ dev/ home/ lib/ mnt/ proc/ sbin/ usr/ boot/ etc/ initrd/ media/ opt/ root/ srv/ tmp/ [malvarez@easynomad1]$ mkdir ~/revenues

var/

The tilde (~) character in the command is a quick way of identifying your home directory.

You now want to set up a subdirectory within the "revenues" directory for each month of the year. To create a "January" subdirectory, you can enter the command
mkdir ~/revenues/January

You then enter a similar command to create subdirectories for every other month.
[malvarez@easynomad1]$ pwd / [malvarez@easynomad1]$ ls bin/ dev/ home/ lib/ mnt/ proc/ sbin/ usr/ boot/ etc/ initrd/ media/ opt/ root/ srv/ tmp/ [malvarez@easynomad1]$ mkdir ~/revenues [malvarez@easynomad1]$ mkdir ~/revenues/January

var/

A quicker alternative is to use the parent or p option to create in one step:


a parent directory revenues a child directory January

a parent directory revenuesa child directory January

[malvarez@easynomad1]$ pwd / [malvarez@easynomad1]$ ls bin/ dev/ home/ lib/ mnt/ proc/ sbin/ usr/ boot/ etc/ initrd/ media/ opt/ root/ srv/ tmp/ [malvarez@easynomad1]$ mkdir ~/revenues [malvarez@easynomad1]$ mkdir -p ~/revenues/January

var/

Suppose that you have now created directories for each month from January to June, but you no longer require the data relating to revenues in January. You can delete the directory just by specifying the path to it in an rmdir command.
[malvarez@easynomad1]$ pwd / [malvarez@easynomad1]$ ls bin/ dev/ home/ lib/ mnt/ proc/ sbin/ usr/ boot/ etc/ initrd/ media/ opt/ root/ srv/ tmp/ [malvarez@easynomad1]$ mkdir ~/revenues [malvarez@easynomad1]$ mkdir -p ~/revenues/January [malvarez@easynomad1]$ rmdir ~/revenues/January

var/

You want to confirm that the January directory in the "revenues" directory has been deleted. You enter ls ~/revenues. The output of the ls command shows that the January directory no longer exists.

[malvarez@easynomad1]$ pwd / [malvarez@easynomad1]$ ls bin/ dev/ home/ lib/ mnt/ proc/ sbin/ usr/ boot/ etc/ initrd/ media/ opt/ root/ srv/ tmp/ [malvarez@easynomad1]$ mkdir ~/revenues [malvarez@easynomad1]$ mkdir -p ~/revenues/January [malvarez@easynomad1]$ rmdir ~/revenues/January [malvarez@easynomad1]$ ls ~/revenues April/ February/ June/ March/ May/

var/

Now suppose that you want to remove all the records of revenues and the ~/revenues directory itself, because the information it contains is no longer needed. To do this, you use the -p option with the rmdir command. So assuming you are already in your home directory, you enter this command.
[malvarez@easynomad1]$ pwd / [malvarez@easynomad1]$ ls bin/ dev/ home/ lib/ mnt/ proc/ sbin/ usr/ boot/ etc/ initrd/ media/ opt/ root/ srv/ tmp/ [malvarez@easynomad1]$ mkdir ~/revenues [malvarez@easynomad1]$ mkdir -p ~/revenues/January [malvarez@easynomad1]$ rmdir ~/revenues/January [malvarez@easynomad1]$ ls ~/revenues April/ February/ June/ March/ May/ [malvarez@easynomad1]$ rmdir -p revenues/* [malvarez@easynomad1]$

var/

The command removes all the empty directories from the revenues directory. If the revenues directory is empty, it removes it also. The asterisk (*) at the end of the pathname specifies that the command must remove all empty directories from within the specified path.

Note
You should be careful when using an asterisk not to delete certain directories accidentally. Now you want to confirm that the revenues directory has been deleted. You enter ls ~. The output of the ls command shows that the revenues directory no longer exists.
[malvarez@easynomad1]$ pwd / [malvarez@easynomad1]$ ls bin/ dev/ home/ lib/ mnt/

proc/

sbin/

usr/

boot/ etc/ initrd/ media/ opt/ root/ srv/ tmp/ [malvarez@easynomad1]$ mkdir ~/revenues [malvarez@easynomad1]$ mkdir -p ~/revenues/January [malvarez@easynomad1]$ rmdir ~/revenues/January [malvarez@easynomad1]$ ls ~/revenues April/ February/ June/ March/ May/ [malvarez@easynomad1]$ rmdir -p revenues/* [malvarez@easynomad1]$ ls ~ Desktop/ Documents/ Pictures/ tmp/ [malvarez@easynomad1]

var/

2. File commands
You can use the shell to manage general files. For example, you can copy files using the cp command with this syntax. cp -option from to You use these options with the cp command:
-b -b -i -v -f -r/-R -p -P -l -s

A copy operation overwrites any existing file with the same name, but the -b option reduces the danger of this operation by creating a backup of the target file.
-i

The -i option forces the shell to prompt you for a yes or no answer before it overwrites any file.
-v

The -v (verbose) option forces the cp command to display a list of files that were copied and the location to which they were copied.
-f

The -f option forces the copy operation to go ahead without prompting for confirmation.
-r/-R

The -r and -R options enable you to copy the contents of a directory and all its subdirectories below a specified path to another directory. Such recursive copying is also possible with complete directory structures.
-p

The -p option enables you to preserve file attributes, including timestamps and permissions.

-P

The -P option instructs the cp command to copy the directory hierarchy, as well as the file or files in a directory.
-l

The -l option instructs the cp command to make hard links between the files in directories, instead of copying them.
-s

The -s option creates a symbolic link from the second named file (the destination) to the first named file (the source), instead of copying.

Question
Suppose that you want to copy files using the cp command, but you'd like the command to report on which files it has copied. Which cp command option must you use in this case? Options: 1. 2. 3. 4.
-b -r -s -v

Answer
You use the -v option to instruct the cp command to display a list of the files it has copied. Option 1 is incorrect. The -b option creates a backup of any file overwritten during a copy operation. Option 2 is incorrect. The r option enables you to copy the contents of a directory and all its subdirectories below a specified path to another directory. Option 3 is incorrect. The -s option creates a symbolic link from the second named file (the destination) to the first named file (the source), instead of copying. Option 4 is correct. The -v option forces the cp command to display the names of files it copied and the locations to which they were copied. To copy data from one device to another from a hard drive to a tape drive or floppy disk, for example you use the dd (device-to-device copy) command with the syntax dd arguments The more common arguments include

if =filename to specify the source file of =filename to specify the output file bs =blocksize to specify how many bytes

to read or write at one time

Suppose that you want to move a file named "January" and consisting of 600 bytes from the "revenues" directory to your floppy disk. To do this, you enter this command:
dd if=/home/revenues/January bs=600 of=/dev/fd0

Note
It is usual to give the name /dev/fd0 to the first floppy drive on the system the one to which you may be most likely to copy files. To move a file or directory to another location, rather than copying it, you use the mv command with this syntax. As with copying files, you should remember that if you move a file to a given location, any file of the same name that already exists at that location will be overwritten without warning. mv option sourcefile targetfile The mv command supports several options, including -b, -i, and -f. mv option sourcefile targetfile The -b option instructs the command to create a backup of the target file, and the -i option instructs it to prompt the user before overwriting a file. The -f option prevents the command from prompting the user before or after moving, deleting, or overwriting a file. As a result, you should use this option with care. You move directories using the mv command. If the target directory does not exist, the command will force the directory to which you instructed it to move to be renamed. However, if it does exist, the mv command will move the source directory to make it a subdirectory of the target directory. mv option sourcefile targetfile You can delete files from the file system by using the rm command. You should remember that once you issue this command, the specified files are lost forever.

Unlike Windows or other operating systems, there is no "recycle" facility in Linux by default although some X Window Systems graphical interfaces do feature one. The rm command supports options including
-i -i -r -f

and -R

The -i option forces the shell to prompt you before deleting files.
-r -f

and -R The -r and -R options recursively delete files. The -f option forces deletion without any prompting.

Question
Which command do you use to place an existing file in a new directory without making a copy of it? Options: 1. 2. 3. 4.
cp dd mv rm

Answer
You move files, rather than copying them, using the mv command. Option 1 is incorrect. The cp command is for copying files. Option 2 is incorrect. The dd command is for cloning the contents of one device onto another device. Option 3 is correct. The mv command moves, rather than copies, files or directories to a new location. Option 4 is incorrect. The rm command is for deleting files, rather than moving them.

3. Information display commands

You can use the wc command with this syntax to return the number of words, lines, or characters in a file. wc options filename(s) With the command, the -c option returns the byte count, the -m option returns the number of characters, the -w option returns the number of words, and the -l option returns the number of lines in a file. You can choose to use more than one of these options in the same command. To verify the type of one or more files, you use the file command with this syntax. file options filename The file command returns the name of the specified file, followed by a brief classification. If you use the -b option with the command, it returns only the classification. Other file command options include -z, for examining compressed files and -f, for reading a list of files to be examined from a prepared text file. The -i option forces the shell to display the file details in Multipurpose Internet Mail Extensions (MIME) type strings, instead of human readable ones. To create a new, empty file or change the date on which an existing file was last accessed or modified, you use the touch command with this syntax. touch options date filename The options for the touch command are
-a -a -m -t -c -d

The -a option enables you to modify the last access time for a file.
-m

The -m option changes the last modification time for a file.


-t

The -t option uses a time that you specify rather than the system time.
-c

The -c option instructs the touch command not to create a new file if one already exists with the same name.
-d

The -d option updates the last modification time for a file. To view the contents of a particular file without opening the file, you can use the cat (concatenation) command with this syntax. cat filename The contents of any file you specify in the command will display on the terminal screen.

Question
What does the command wc w myfile do? Options: 1. Return the number of characters in a file named myfile 2. Return the number of lines in a file named myfile 3. Return the number of words in a file named myfile

Answer
The command wc w myfile returns the number of words in a file named myfile. Option 1 is incorrect. The command wc m myfile would return the number of characters in a file named myfile. Option 2 is incorrect. The command wc l myfile would return the number of lines in a file named myfile. Option 3 is correct. The w option instructs the wc command to return the number of words in the specified file.

Summary
You can use a number of commands to identify and manipulate the location and contents of directories. Identifying commands for directories include pwd and ls, and manipulation commands include cd, mkdir, and rmdir. The cp, dd, mv, and rm commands enable you to copy files to new locations, to copy them between devices, to move files, and to delete files respectively. One of the most useful options with these commands is -i, because it requires the shell to prompt you before performing any tasks. You can use the command prompt to access general information on files and to view their contents. Some of the main commands for doing this include wc, touch, file, and cat.

Table of Contents

Special characters on the Linux command line


Abstract
This article describes how to use metacharacters characters with special meanings in Linux commands to perform operations such as filename completion and command substitution. It also describes how to escape or modify the special meaning of metacharacters.

Introduction
Specially defined characters are essential for many of the Linux shell's powerful features, such as filename completion and command substitution. The shell interprets these characters in a different way from other, regular characters on the command line. However, if you want to disable these characters, you can use a process called quoting.

Filename completion characters


Filename completion characters are metacharacters that enable you to abbreviate filenames or directory names. This saves time and lets you process files selectively, even if you don't know their full names or locations. Commonly used filename completion characters are included in the table below. Filename completion characters Character Meaning Matches zero or more characters * (asterisk) Matches any single character ? (question mark) [] (square brackets) Matches a single character in a range Identifies a variable $ (dollar sign) Represents the home directory ~ (tilde character) The * character (asterisk) is the most frequently used file completion character. You can use the string b*, for example, to match all the filenames beginning with the letter "b". You can also use multiple asterisks to define a file. For example, *xx*.gif retrieves any filename that contains "xx" anywhere in its name and that has the .gif extension.

The ? character (question mark) represents any single character, so the string ??? refers to all files with a three-letter name. This special character is more restrictive than the asterisk, because it requires the character to be present. For example, the code file?.txt signifies all files that begin with "file", include one additional character, and have the .txt extension. So the filename "file1.txt" matches, but "file.txt" and "file01.txt" don't. Using [] characters (square brackets) allows for a more selective approach to retrieving files. The string [abc] will find files a, b, and c only. You can include a hyphen between characters inside the brackets to match a continuous range of characters. To specify the characters 0 through 9, for example, it is a lot easier and less time-consuming to type [0-9] rather than [0123456789]. If the brackets precede an asterisk, as in [0-9]*, filenames starting with any numbers between 0 and 9 are found. The pattern *[0-9] will match filenames ending with numbers between 0 and 9. Inserting an exclamation mark inside the brackets, as in [!b], will invert the pattern, matching any characters or ranges not specified in the brackets but ignoring those that are. In Linux, the different types of grouping characters are ( ) - commonly referred to as parenthesis. May also be referred to as open, or round, brackets { } - commonly referred to as braces or curly brackets [ ] - most often referred to as brackets or square brackets The $ (dollar sign) is used to identify shell variables at the command line. Variables are values that have been associated in memory with some kind of identifier. Variables have many uses in Linux. To give a simple example, a variable with the identifier PATH contains the list of directories within which the shell can search for executable files. To view this list, you invoke the following command:
echo $PATH

If you entered the command echo PATH, it would print the literal string "PATH", rather than the value of the PATH variable, on your terminal. The ~ character (tilde) enables you to refer quickly and easily to your home directory, no matter where in the file system you might be. Say that your current working directory is /usr/local/bin and you have a file called "usernames" in your own home directory, which you want to edit with vi. Rather than having to type the complete path to the file, you can just issue the command
vi ~/usernames

Quoting special characters


There are occasions when you might want to suppress the special meanings of metacharacters. A special character must be quoted in order to represent its own literal meaning rather than its

special meaning to the shell. Quoting causes the shell to overlook the unique capabilities of special characters and negate parameter expansion. This mechanism uses the following quote symbols:
\ " ' `

(backslash) (double quotes) (single quotes) (backquote)

The backslash is also known as the bash shell escape character. This is because it turns off or "escapes" the special meaning of the character that follows it. For example, as we have already seen, the following command returns the value of the PATH environment variable:
echo $PATH

However, the following command will return the literal output "$PATH", because the backslash negates the special meaning of the dollar sign:
echo \$PATH

If a line itself ends with a backslash, it acts as a continuation character for the line and the newline character is ignored. Single quotes negate the translation of all special characters. They prevent the substitution of alternative values for the characters. For example, the following command will output a list of single-character filenames:
ls ?

However, this command will attempt to list the file with the literal name "?":
ls '?'

Double quotes cause most metacharacter special meanings to be ignored. The exceptions to this rule are the dollar sign, backquote, and backslash. So double quotes have the effect of canceling the process of filename generation by the shell, but still allow the expansion of shell variables and command substitution. The dollar sign and backquote continue to function as special characters when included between double quotes. The backslash character only does so when it's followed by a dollar sign, backquote, double quote, backslash, or a newline character. In these circumstances, the backslash itself is removed and the special meaning of the following character is ignored. This makes it possible to quote a double quote between double quotes if it is preceded by a backslash. For example, the commands echo"\"" or echo\" output a double quote character by suppressing the special meaning of the embedded double quote. The backquote is still often used for command substitution, although the $() combination (a dollar sign and parenthesis) is generally preferred. The shell interprets the text between a pair of

backquotes as a command before translating the rest of the command line. The output of the command replaces the original backquoted text. In the following code, the double quotes disable the date command:
> echo "date" date

However, the backquotes in this command enable command substitution to occur:


>echo `date` Thu Jun 10 17:18:56 IST 2004

Summary
Linux supports a wide range of metacharacters, which are characters that have special meanings in commands. Metacharacters let you enter commands more succinctly, and refine the behavior of commands so that you can obtain more precise output. They also enable you to execute a single command against multiple files. To escape the special meaning of a metacharacter, you can enclose it in quotation marks or precede it with a backslash (\).

Table of Contents
| Print | Contents | Close |

Managing the Linux Shell Environment


Learning objective
After completing this topic, you should be able to interact with the shell environment.

1. Environment variables
The Linux shell is configured with a number of default settings, known as environment variables. Each environment variable is a storage area in memory that contains a value. The values of environment variables determine the behavior of the shell. Environment variables therefore affect the performance and appearance of the shell environment. The main environment configuration information for the shell is defined in the /etc/profile file.

The SHELL environment variable determines shell behavior. It defines the environment in which a user works by determining how the shell behaves and how it interprets commands to the Linux operating system. One of the most important environment variables is PATH. This variable tells the shell where to look for files and commands. If, for example, some commands are stored in an additional directory, you can adjust the value of the PATH variable to include this directory in searches. If you enter the path command, your current path displays.
[mgomez@easynomad1]$ path /usr/bin: /bin: /usr/bin:/usr/local/bin:/usr/X11R6/bin/:/usr/games:/home/mgomez/bin [mgomez@easynomad1]$

The HOME environment variable defines the path to the home directory, and the USER environment variable contains the identity of the person currently logged on. The PWD environment variable defines the user's current working directory. Entering the pwd command displays your current working directory.
[mgomez@easynomad1]$ pwd /home/mgomez [mgomez@easynomad1]$

Other significant environment variables include HISTFILE, HISTFILESIZE, and HISTSIZE. These environment variables all relate to command history. The command history is stored in the ~/.bash_history file, and enables you to view and edit previously entered commands. The HISTFILE variable specifies the file that stores command history, HISTFILESIZE specifies the maximum size of the file, and HISTSIZE determines the number of entries the ~/.bash_history file can store.

Question
Match each shell environment variable to its description. Options: 1. HOME 2. PATH 3. SHELL

Targets: 1. Defines the environment in which the user is currently working 2. Defines the path to the user's home directory 3. Tells the shell where to look for files and commands

Answer
The HOME environment variable defines the path to the user's home directory, PATH tells the shell where to look for files and commands, and SHELL defines the environment in which the user is currently working. The HOME environment variable identifies the path to the working directory of the currently logged-on user. The configuration files that define environment variables are usually stored in the home directory. The PATH variable defines the directories that the shell must search for commands. You can adjust the value of the PATH variable to include an additional directory in searches. The SHELL environment variable determines how the shell behaves, and how it interprets users' commands to the Linux operating system. Environment variables are usually defined in configuration files. These are stored in either the /etc directory or the ~ directory, which is usually the logged-on user's home directory. The main environment configuration information for the SHELL environment variable is defined in the /etc/profile file.

2. Referencing environment variables


When you define the value of a variable using the syntax variable = value, the value applies only within the current shell. This variable is a local variable. To ensure that a variable value is inherited by child processes and subsequent shells, you need to issue the command using the syntax export variable. When a variable is inherited in this way, it is known as an exported variable. To display all local and exported variables in the shell, you use the set command.
[malvarez@easynomad1 malvarez]$ pwd /home/malvarez [malvarez@easynomad1 malvarez]$ set

The set command returns a list of environment variables and their values in the form name=name.

TERM=xterm TMOUT=0 TMP=/home/malvarez/tmp TMPDIR=/home/malvarez/tmp UID=503 UMASK_ROOT=022

Supplement
Selecting the link title opens the resource in a new browser window. Launch window View the full output of the set command. To display exported environment variables in the shell only, you enter the env command.
[malvarez@easynomad1 malvarez]$ pwd /home/malvarez [malvarez@easynomad1 malvarez]$ env

The env command returns exported variables only.


HELP_BROWSER=kfmclient openProfile webbrowsing LC_MEASUREMENT=en_US PS1=[\u@\H]$ HISTCONTROL=ignoredups SHLVL=2 HOME=/home/malvarez

Supplement
Selecting the link title opens the resource in a new browser window. Launch window View the full output generated by the env command. You can display only the value of a particular variable using this syntax.
[malvarez@easynomad1 malvarez]$

echo $VARIABLE_ NAME To find out what the current system path is, for example, you enter
echo $PATH [malvarez@easynomad1 malvarez]$ echo $PATH

Note
The variable name you enter must be written in capital letters to indicate that it is an environment variable. To display your current working directory, which the PWD environment variable stores, you enter the pwd command.
[malvarez@easynomad1 malvarez]$ pwd

And the name of the directory displays.


/home/malvarez [malvarez@easynomad1 malvarez]$

To make changes to environment variables, you use the built-in export command.
[malvarez@easynomad1 malvarez]$

For example, suppose that you want to add the ~ /Desktop directory to the PATH variable in your shell. To do this, you enter this code.
[malvarez@easynomad1 malvarez]$ PATH=$PATH:~/Desktop

To ensure that you've added the ~/Desktop directory correctly, you enter the echo $PATH command.
[malvarez@easynomad1 malvarez]$ PATH=$PATH:~/Desktop [malvarez@easynomad1 malvarez]$ echo $PATH

The list of directories that the PATH variable contains is displayed.


[malvarez@easynomad1 malvarez]$ PATH=$PATH:~/Desktop [malvarez@easynomad1]$ echo $PATH /usr/bin:/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin/:/usr/games:/home/malvar ez/bin:/home/malvarez/Desktop [malvarez@easynomad1 malvarez]$

To return to your home directory, you use any one of these commands:
cd cd ~ cd $HOME

If you want a new environment variable to stay the same for child processes, you need to export it by using this command syntax.
[malvarez@easynomad1 malvarez]$ PATH=$PATH:~/Desktop [malvarez@easynomad1]$ echo $PATH

/usr/bin: /bin:/user/bin:/usr/local/bin:/usr/X11R6/bin/://usr/games:/home/malvarez/bin: /home/malvarez/Desktop [malvarez@easynomad1 malvarez]$

export VARIABLE_ NAME For example, if you want to ensure that the ~/Desktop directory is included in the PATH variable even if you switch to another shell, you enter
export PATH [malvarez@easynomad1 malvarez]$ PATH=$PATH:~/Desktop [malvarez@easynomad1]$ echo $PATH /usr/bin: /bin:/user/bin:/usr/local/bin:/usr/X11R6/bin/://usr/games:/home/malvarez/bin: /home/malvarez/Desktop [malvarez@easynomad1 malvarez]$ export PATH

It is important to remember that the adjustments made by the export command last only until you log out of the shell. If you want to change the values of any environment variable permanently, you need to edit the .bash_ profile file in your home directory. To make changes that will apply to all users, you need to edit the /etc/profile file as the root user.

Question
Match each command to its function. Options: 1. env 2. export 3. set Targets: 1. Displays a selection of shell environment variables 2. Displays a list of all environment variables 3. Ensures that a new environment variable stays the same for child processes

Answer
The env command displays a selection of shell environment variables. The export command ensures that a new environment variable is retained for child processes. And the set command lists all environment variables.

The env command displays only exported shell environment variables. The export command enables a new environment variable to stay the same for child processes, but only for a current session. Once you log out of the shell, the adjustments made by the export command fall away. The set command returns a list of all environment variables and their values in the form name=name. You can sometimes use special characters when setting the values of environment variables. For example, you can change the PS1 or prompt variable by using this syntax, which may include special characters. PS1="[characters]\PROMPT" In this syntax, PROMPT is a single character, usually $ or #. Some of the special characters that you can use when changing the value of the PS1 prompt are
\d \d \h \u \w \t \s

The \d character displays the date in the "Weekday Month Date" format, as in Mon Apr 23.
\h

The \h character displays the host name.


\u

The \u character displays the username of the current user.


\w

The \w character displays the current working directory of the logged-on user.
\t

The \t character displays the time, in 24-hour HH:MM:SS format.


\s

The \s character displays the name of the shell. Suppose that you want to change the bash prompt from a dollar sign ($) to a hash sign (#), and to include your username, your working directory, and the time to appear at the prompt.
[malvarez@easynomad1 malvarez]$ PS1="[\u \w \t]#"

To do this, you enter this command.

The new prompt displays.


[malvarez@easynomad1 malvarez]$ PS1="[\u \w \t]#" [malvarez malvarez 15:22:08]#

Question
What does the command PS1="[\h \w \t]$" include in the prompt that the PS1 environment variable stores? Options: 1. 2. 3. 4. The current working directory of the logged-on user The date, in the format "Weekday Month Date" The host name The time, in 24-hour format

Answer
The command displays the host name, the time in 24-hour format, and the logged-on user's current working directory in the prompt. Option 1 is correct. The \w character in the command displays the user's working directory at the command prompt. Option 2 is incorrect. The command does not include the \d character, which displays the date in the prompt. Option 3 is correct. The \h character in the command displays the host name in the default prompt command. Option 4 is correct. The \t character in the command displays the time in 24-hour format at the command prompt. To remove a variable or function from the shell, you use the unset command with this syntax. unset arguments NAME You use the -f argument to direct the operating system to remove a function, and you use the -v argument to tell the system to unset a variable. If you don't use an argument with the unset command, the system first attempts to remove variables and then to remove functions. The unset command differs from setting the variable to no value using the syntax

VARIABLE_NAME= Using the unset command removes a variable from memory completely. As a result, this command doesn't work with environment variables such as PATH or PS1, which are both readonly variables.

Summary
Environment variables store values that control how the shell looks and functions. Important environment variables include SHELL, which determines shell behavior, and PATH, which identifies the path to the user's home directory. Other important environment variables include HISTFILE, HISTFILESIZE, and HISTSIZE, which relate to command history. You can view all of the environment variables in the shell using the set command. The env command lets you view just the exported variables, while the export command lets any amended variables remain in existence in child processes until you log out of the shell. To delete a variable from the shell environment, you use the unset command.

Table of Contents
| Top of page |

Setting the PATH Variable in Linux


Learning objective
After completing this topic, you should be able to set the PATH environment variable in a secure way.

Exercise overview
In this exercise, you're required to modify the value of the PATH environment variable. This involves the following tasks:

checking the settings of the PATH variable identifying your home directory appending your home directory to the value of the PATH variable

Suppose that you are Pierre Leblanc, a travel consultant with the Easy Nomad travel company. You want to append your home directory to the current path.
[pleblanc@easynomad1 tmp]$

Task 1: Checking the PATH setting


First, you need to determine what the current path is.

Step 1 of 1
To determine the current path, you check the current value of the PATH environment variable. Enter the command that displays the current value of the PATH environment variable.
[pleblanc@easynomad1 tmp]$ MISSING CODE

Result
To determine the current system path, you enter echo $PATH. The current path is displayed.
[pleblanc@easynomad1 tmp]$ echo $PATH /usr/bin:/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin/:/usr/games:/home/plebla nc/bin [pleblanc@easynomad1 tmp]$

Task 2: Identifying the home directory


Once you've checked the current value of the PATH environment variable, you need to check the path to your home directory so that you can append this path to the existing path that the PATH variable stores.

Step 1 of 2
You first need to return to your home directory. Enter the command that returns you to the home directory.
[pleblanc@easynomad1 tmp]$ echo $PATH /usr/bin:/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin/:/usr/games:/home/plebla nc/bin [pleblanc@easynomad1 tmp]$ MISSING CODE

Result
You type cd, cd ~, or cd $HOME to return to the home directory.

You've returned to the home directory.


[pleblanc@easynomad1 tmp]$ echo $PATH /usr/bin:/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin/:/usr/games:/home/plebla nc/bin [pleblanc@easynomad1 tmp]$ cd [pleblanc@easynomad1 pleblanc]$

Step 2 of 2
Once you're in the home directory, you want to check the full path to this directory. Which command displays the full home directory path?
[pleblanc@easynomad1 tmp]$ echo $PATH /usr/bin:/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin/:/usr/games:/home/plebla nc/bin [pleblanc@easynomad1 tmp]$ cd [pleblanc@easynomad1 pleblanc]$ MISSING CODEMISSING CODE

Options: 1. echo $PATH 2. export PATH 3. pwd

Result
You enter pwd to display the full path of your current directory. Option 1 is incorrect. You use the echo $PATH command to display the current system path. If, for example, you've added a directory to PATH, you can use the echo $PATH command to check that you've added it correctly. Option 2 is incorrect. You use the export PATH command to ensure that a directory that you've added to the PATH variable is included even when you switch to another shell. Option 3 is correct. You use the pwd command to display the full path of the logged-on user's current working directory. This command tells you where a user's home directory is in the file system. The path to the home directory displays.
[pleblanc@easynomad1 pleblanc]$ pwd /home/pleblanc [pleblanc@easynomad1 pleblanc]$

Task 3: Altering the PATH value


You now want to append your home directory to the current path in the PATH environment variable.

Step 1of 1
Which command do you use to append the home directory to the shell's PATH environment variable?
[pleblanc@easynomad1 tmp]$ echo $PATH /usr/bin:/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin/:/usr/games:/home/plebla nc/bin [pleblanc@easynomad1 tmp]$ cd [pleblanc@easynomad1 pleblanc]$ pwd /home/pleblanc [pleblanc@easynomad1 pleblanc]$E MISSING CODE

Options: 1. $PATH:/home/pleblanc 2. $PATH=$PATH: /home/pleblanc 3. PATH=$PATH:/home/pleblanc

Result
You use this command to append your home directory to the shell's PATH environment variable:
PATH=$PATH:/home/pleblanc

Option 1 is incorrect. This will result in a shell error message such as "No such file or directory." Option 2 is incorrect. There should not be a $ sign preceding the PATH parameter on the left of the = sign. Option 3 is correct. This command issues an instruction to the shell to change the system path by appending the home directory. You have now appended the home directory to the PATH environment variable.
[pleblanc@easynomad1 pleblanc]$ pwd /home/pleblanc [pleblanc@easynomad1 pleblanc]$ PATH=$PATH:/home/pleblanc [pleblanc@easynomad1 pleblanc]$

To confirm that the operation was successful, you enter the echo $PATH command
echo $PATH [pleblanc@easynomad1 pleblanc]$ pwd /home/pleblanc [pleblanc@easynomad1 pleblanc]$ PATH=$PATH:/home/pleblanc [pleblanc@easynomad1 pleblanc]$ echo $PATH

The output confirms that you have successfully appended your home directory to the path in the PATH environment variable.
[pleblanc@easynomad1 pleblanc]$ pwd /home/pleblanc [pleblanc@easynomad1 pleblanc]$ PATH=$PATH:/home/pleblanc [pleblanc@easynomad1 pleblanc]$ echo $PATH /usr/bin:/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin/:/usr/games:/home/plebla nc/bin:/home/pleblanc [pleblanc@easynomad1 pleblanc]$

Table of Contents
| Print | Contents | Close |

Command History and Editing in Linux


Learning objective
After completing this topic, you should be able to use the history facility and edit previously entered commands.

1. Displaying command history


As administrator, you may sometimes need to enter long commands or long sequences of commands that are difficult to remember. The shell has the capacity to store issued commands in its memory. Each issued command is known as an event, and each event is assigned a number by the shell. The more recent an event, the higher its assigned number. These shell environment variables control the number and location of events in memory:
HISTFILE HISTSIZE HISTFILESIZE

HISTFILE

The HISTFILE variable specifies the file in which the shell saves your history list. By default, this file is the .bash_history file in your home directory. If you don't give a filename to this variable or if the file you specify doesn't accept write operations, past events won't be saved.
HISTSIZE

The HISTSIZE variable specifies the number of events to be preserved in memory known as the history list during a particular login session.
HISTFILESIZE The HISTFILESIZE specifies the maximum number of events HISTFILE variable can store. The default value is 1000.

that the file specified in the

Question
Match each shell environment variable to the value it stores. Options: 1. HISTFILE 2. HISTFILESIZE 3. HISTSIZE Targets: 1. The file in which the shell saves the history list 2. The number of events kept in memory during a particular login session 3. The number of events that a history file can store

Answer
The HISTFILE variable specifies the file to which the shell saves the history list, the HISTSIZE variable specifies the number of events kept in memory during a particular login session, and the HISTFILESIZE variable specifies the maximum number of events that the history file can store. The HISTFILE variable specifies the file in which the shell saves previously issued commands, or events. By default, this is the .bash_history file in the home directory. The HISTFILESIZE variable specifies the maximum number of events that the history file can store. If you don't give a value to this variable, no limitation is placed on the size of the file. The HISTSIZE variable specifies the number of events that the shell must keep in memory during a login session. These events are known as a history list. To view past events, you can use the up and down arrow keys.

When you press the up arrow key, a previous event displays. To display a particular previous event, you scroll back to it by pressing the up arrow key repeatedly until it displays. To move forward through the list, you use the down arrow key. Instead of using the up and down arrow keys, you can display a list of past events by entering the history command at the shell prompt.
[malvarez@easynomad1 malvarez]$ history

The output of the history command displays all the events in the history list.
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 cd /home cat .bashrc cat .bashrc [malvarez@easynomad2 ~] clear fc -1 cd cat fc - nl cd cat -n clear fc -1 history fc -1 history history fc -1 man fc info fc help fc fc -l

Supplement
Selecting the link title opens the resource in a new browser window. Code window View the output of the history command. If you are interested only in the last ten events in a history list, for example, you enter the command
history 10 [malvarez@easynomad1 malvarez]$ history 10

And the ten most recently issued commands display.


[malvarez@easynomad1 malvarez]$ history 10 279 ! -11 280 fc -5 281 ls /ust

282 ls /usr 283 clear 284 fc -l cd cat > code_fclcdcat_output 285 fc -1 35 43 286 fc -l 35 43 > code_fcl3543_output 287 fc -l 35 43 288 history 10 289 history 10 > code_history10_output [malvarez@easynomad1 malvarez]$

To manipulate how past events are saved, you can use the history command with a number of options. In the syntax for doing this, filename refers to the file in which past events have been saved. By default, this is the ~/.bash_history file. history options filename The history command supports these options:
-w -w -a -r -n

The -w option writes the current history list to the history file.
-a

The -a option appends the history lines entered since the beginning of the current session to the history file.
-r

The -r option reads the current history file and appends its contents to the history list.
-n

The -n option updates the history list with any lines from the history file that haven't already been accessed and read in the current bash session.

Question
Suppose that you want to update the history list with lines that have been appended to the history file since the beginning of the current bash session. Which option do you use with the history command to do this? Options: 1. -a 2. -n 3. -r

4. -w

Answer
You use the -n option with the history command to update the history list with lines from the history file that have been appended to the history file since the beginning of the current bash session. Option 1 is incorrect. The -a option appends history lines entered since the beginning of the current session to the history file. Option 2 is correct. The -n option updates the history list with any lines from the history file that have been appended to the history file since the beginning of the current bash session. Option 3 is incorrect. The -r option reads the current history file and append its contents to the history list. Option 4 is incorrect. The -w option writes the current history list to the history file. In addition to the history command, you can use the fc command with this syntax to display past events. fc options arguments To view a list of past events, you enter the command
fc -l [malvarez@easynomad1 malvarez]$ fc -l

This displays the last 16 events in the history list. When the -l option is given, the commands are listed as standard output. Otherwise, the default editor is invoked on a file containing those commands.
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 history fc -1 man fc info fc help fc fc -l clear fc -l fc -l >code_window_fcl_output history 10 > code_window_history10_output history history > code_window_history_output clear history10 clear

191 192

history 10 clear

[malvarez@easynomad1 malvarez]$

To view a specific range of commands, you can enter their event numbers as arguments for the fc -1 command. To view a list of events numbered 35 to 43, for example, you enter
fc -l 35 43 [malvarez@easynomad1 malvarez]$ fc -l 35 43

This displays events numbered 35 to 43


35 vncserver 36 set > set_command 37 env > env_command 38 echo $PATH > echo_path 39 PATH=$PATH:~/Desktop > pathpath_desktop 40 PATH=$PATH:~/Desktop 41 pwd 42 set > Michelle/set_command 43 umount /mnt/stick1 [malvarez@easynomad1 malvarez]$

To search for a range of past events by name for example, from the most recently issued command that begins with cd up to the most recently issued command beginning with cat you enter
fc -l cd cat [malvarez@easynomad1 malvarez]$ fc -l cd cat

The output of the command displays the requested events only.


[malvarez@easynomad1 malvarez]$ fc -l cd cat 164 cd /home 165 cat .bashre 166 cat /.bashre [malvarez@easynomad1 malvarez] $

To prevent line numbers from being displayed with the command names in an event history, you use the -n option with the fc command. For example, you enter this command to return just the previously entered cd and cat commands.
[malvarez@easynomad1 malvarez] $ fc -nl cd cat

This returns a list of cd and cat commands, without line numbers.

[malvarez@easynomad1 malvarez] $ fc -nl cd cat cd /home cat .bashre cat /.bashre[malvarez@easynomad2 ~] [malvarez@easynomad1 malvarez] $

2. Rerunning and editing comments


Occasionally, you may want to rerun or edit certain commands that you have already issued. You do this by issuing the fc command with various options. To re-execute a specific event or command, you use the fc command with this syntax.
[malvarez@easynomad1 malvarez]$ fc -s 49

fc -s command For example, to re-execute event 49, you enter


fc -s 49

To rerun only the last event, displaying only the name of the shell, you enter
fc -s [malvarez@easynomad1 malvarez]$ fc -s

A shorter way to re-execute an event is to type an exclamation mark (!) at the command line. To re-execute the most recent event, you enter
!! [malvarez@easynomad1 malvarez]$ !!

To re-execute a specific event for example, event number 475 you enter
!475 [malvarez@easynomad1 malvarez]$ !475

You can use an exclamation mark (!) with the first character of a command to identify and reexecute the command. For example, to find and re-execute a command beginning with the character "m," you enter this command.
[malvarez@easynomad1 malvarez]$ !m

In this example, the command finds and re-executes a mail-related event.

[malvarez@easynomad1 malvarez]$ !m mail Mail version 8.1.1 6/6/93. Type ? for "/var/spool/mail/malvarez": 2 messages >U 1 ksmith@easynomad.com Tue Jun 1 U 2 ksmith@easynomad.com Tue Jun 1 &

help. 2 unread 08:17 17/543 09:52 17/543

If you know the exact order of your commands and you want to reissue one of them, you can type the number of the command relative to your current command. For example, if you wish to re-execute the tenth command prior to the current command, you enter
!-10

Note
You may need to add more than one character after the ! command. For example, if you want to re-execute a cp command to copy one file to another, but have issued a cd command to change directory since you last issued the cp command, you need to enter the command
!cp

Simply typing !c will result in the cd command being re-executed. You use the fc command with the -e option to edit previous commands. fc -e texteditor [command] For example, this command enables you to edit the previously entered command using the vi editor:
fc -e vi [malvarez@easynomad1 malvarez]$ cd ~/Documents [malvarez@easynomad1 malvarez]$ fc -e vi

Once you've entered the command fc -e vi, you can edit the previously entered command cd ~/Documents. The command will be executed when you finish editing it.
cd ~/Documents ~ ~ ~ ~ ~

To edit a specific past event with the vi text editor, you enter the command number of the event. For example, you type this command to edit event 366 using the vi text editor.
[malvarez@easynomad1 malvarez]$ fc -e vi 366

Once you enter the command, you can edit command number 366, which is a command to list the contents of the /home/malvarez directory in long format, in the vi editor. To specify an alternative text editor emacs, for example in the command line, you enter this command.
[malvarez@easynomad1 malvarez]$ fc -e emacs 233 245

This issues a command to the shell to edit events 233 to 245 with the emacs text editor.
! -8 history ! -11 fc -5 ! -10 export PS1=\[$SHELL\]\$ clear fc -5 export PS1=\[$SHELL\]\$ clear ! -8 clear fc -e vi

To change the default text editor permanently, you use the export command and the FCEDIT variable. export FCEDIT=text editor pathname

Question
Which command enables you to edit a specific event using the vi editor? Options: 1. export FCEDIT=/usr/bin/vi 2. fc -e emacs 500 3. fc -e vi 500

Answer
The command fc -e vi 500 enables you to edit a specific past event with the vi text editor.

Option 1 is incorrect. This is the command you use to change permanently to the vi text editor if the default text editor had been set to another editor, such as emacs. Option 2 is incorrect. The command fc -e emacs 500 specifies the alternative text editor, emacs, and enables you to edit command number 500 using that text editor. Option 3 is correct. To edit a specific past event with vi, you use the command fc -e vi, and the command number. For example, fc -e vi 500 enables you to edit command number 500. You use this syntax to repeat a command with a substitution.
[malvarez@easynomad1]$ ls /ust ls: /ust: No such file or directory [malvarez@easynomad1]$

^oldtext^newtext Suppose that you've mistyped a directory path when issuing a command. For example, suppose that you typed ls /ust instead of ls /usr at the shell prompt.
[malvarez@easynomad1 malvarez]$ ls /ust ls: /ust: No such file or directory

If you now enter ^t^r at the prompt, the shell will reinterpret the previous command and replace the t in /ust with an r.
[malvarez@easynomad1]$ ls /ust ls: /ust: No such file or directory [malvarez@easynomad1]$ ^t^r

The command with the correct text in place is echoed to the terminal screen, and you execute it by pressing Enter.
[malvarez@easynomad1]$ ls /ust ls: /ust: No such file or directory [malvarez@easynomad1 malvarez]$ ^t^r ls/usr /bin /games /lib /postinstall-rpm /share /tmp@ /etc /include /local /sbin /src /X11R6 [malvarez@easynomad1 malvarez]$

Question
What is the syntax for repeating a command using a substitution? Options: 1. ^newtext^oldtext 2. ^oldtext^newtext

3. fc -e texteditor [command]

Answer
The syntax you use to repeat a command using a substitution is ^oldtext^newtext. Option 1 is incorrect. The correct syntax for substituting text in an incorrectly typed command requires the incorrect text followed by the correct text. A command that uses the syntax ^newtext^oldtext will cause the shell to re-interpret the previous command without making any changes to it. Option 2 is correct. To correct an incorrect entry you've just made, you specify the old text, followed by the text with which you want to replace it. Before each entry, you enter a caret (^) symbol. If, for example, you enter ^t^r at the prompt, the shell will replace t in the previous command with r. Option 3 is incorrect. You use this syntax to edit the previous command with a specific text editor. For example, you'd enter fc -e pico to change the previous event using the pico text editor.

Summary
The Linux shell usually stores issued commands, known as events, in memory in the .bash_history file in the logged-on user's home directory. The variables HISTFILE, HISTSIZE, and HISTFILESIZE control the number and location of stored events. To view previous events, you scroll using the up or down arrow on your keyboard, you issue the history command, or you issue the fc command on its own or with specific command names or numbers. You use the fc command with the -s option to re-execute events. You can also enter an exclamation mark (!) at the prompt to execute commands. To edit previous commands, you reenter them, substituting text in the command. Alternatively, you edit commands using fc with the -e option. The default text editor is vi, but you can specify an alternative editor at the command prompt. Print | Contents | Close |

Command Substitution and Command Paths in Linux


Learning objective
After completing this topic, you should be able to use some of the advanced facilities of the command line.

1. Using file completion characters


In Linux, you can use filename completion characters known as wildcards to save time when specifying files and parameter strings. The asterisk (*) is the most wide-ranging wildcard. It enables you to refer to any or all characters in any sequence. Suppose that your current directory is home/grosetti/Network. You want to list all files in the current directory that end with .txt, and that contain the letters "st" anywhere within their names. You enter this command to list the files.
[root@easynomad1 grosetti]# ls *st*.txt

The command ls *st*.txt produces the files list.txt, roster.txt, staff.txt, and systems.txt.
[root@easynomad1 Network]# ls *st*.txt list.txt roster.txt staff.txt systems.txt [root@easynomad1 Network]#

To list all files in your current directory that end with the letters "txt", you enter this command.
[root@easynomad1 Network]# ls *txt

The command ls *txt displays all files that include the .txt extension.
[root@easynomad1 Network]# ls *txt Filing.txt reviews.txt staff.txt list.txt roster.txt systems.txt [root@easynomad1 Network]# text_only.txt vacations.txt

The question mark (?) wildcard enables you to denote a single required character only. Suppose that you have a number of files for example, jobs1, jobsb, jobs_backlog, and jobs2.txt and you want to list the first two files in long format. To do this, you enter this command.
[root@easynomad1 Network]# ls -l jobs?ls -l jobs?

The command ls -l jobs? displays the details of the files jobs1 and jobsb on the terminal screen.
[root@easynomad1 Network]# ls -l jobs? -rw-rw-r-- 1 grosetti grosetti 8360 Jun -rw-rw-r-- 1 grosetti grosetti 8360 Jun [root@easynomad1 Network]# 2 10:33 jobs1 2 10:33 jobsb

To list all files with names that are four characters long and that end in "r", you enter
ls ???r [root@easynomad1 Network]# ls ???r door soar star [root@easynomad1 Network]#

Question
Suppose that you want to display all files in the current directory that have three characters in their names, and that end in the letter "x". What is the command you issue to display these files? Options: 1. ls **? 2. ls ???x 3. ls ??x

Answer
You use the ls ??x command to display all files in the current directory that have three characters in their names, and that end in the letter "x". Option 1 is incorrect. The asterisk (*) wildcard tells the shell to display files that match the character or sequence of characters preceding it. You use the question mark (?) wildcard to denote a single required character only. Option 2 is incorrect. The number of characters you specify after the ls command specify the number of characters you mean the file names to contain. So the command ls ???x tells the shell to display files with four characters in their names, the last of which is the letter "x". Option 3 is correct. The command ls ??x sends an instruction to the shell to display files with three characters in their names denoted by "??x" the last of which is the letter "x". Square brackets ([]) enable you to be more selective when referring to files. You use square brackets to specify a particular series of values, or to list a range of characters to be matched.
[root@easynomad1 Network]# ls [MP]*

To list all files in your current directory that begin with an uppercase "M" or an uppercase "P," for example, you enter
ls [MP]*

The command returns filenames that begin with "M" or "P."


[root@easynomad1 Network]# ls [MP]* Maria_settings Miguel_settings Pierre_settings [root@easynomad1 Network]#

If you enter this command, the shell displays all files with names that end in a number:
ls *[0-9] [root@easynomad1 Network]# ls *[0-9] batchfile_0211 permissions3 project_team11:32:44-02_06_2004 jobs1 project_team11:30:33-02_06_2004 reviews2 [root@easynomad1 Network]#

staff2

Note
Filenames in Linux are case sensitive. So, for example, entering the command ls [a-z]* displays all files beginning with a lowercase letter. You can use square brackets ([ ]) to define a sequence of allowed characters. For example, suppose that your working directory is /home/grosetti/staff_needs. It contains a list of files named software.00, software.96, software.97, software.98, and software.99.
[root@easynomad1]# ls software.00 software.96 software.97 software.98 software.99 [root@easynomad1 staff_needs]#

You want to move only the software.96, software.97, and software.98 files to a directory named ~/past_upgrades.
[root@easynomad1]# ls software.00 software.96 software.97 software.98 software.99 [root@easynomad1 staff_needs]# mv software.9[678] ~/past_upgrades [root@easynomad1 staff_needs]#

You enter mv software.9[678] ~/past_upgrades at the command prompt. The three files have now been moved to the ~/past_upgrades directory.
[root@easynomad2 staff_needs]# pwd/home/grosetti/staff_needs[root@easynomad2 staff_needs]# ls software.00 software.96 software.97 software.98 software.99 [root@easynomad2 staff_needs]# mv software.9[678] ~/past_upgrades [root@easynomad2 staff_needs]#

You use the ls command to confirm that the files have moved.

[root@easynomad1 staff_needs]# ls ~/past_upgrades software.96 software.97 software.98 [root@easynomad1 staff_needs]#

Question
What command do you enter to display a list of all files in the current directory with names that end with the numbers 5, 6, 7, or 8? Options: 1. 2. 3. 4.
ls *[5678] ls [5678] mv [5678]* pwd [5678]

Answer
You use this command to display a list of files with names that end with the numbers 5, 6, 7, or 8:
ls *[5678]

Option 1 is correct. You use the square brackets ([]) to define a sequence of allowed characters, and the ls command displays the files in the current working directory. The asterisk (*) refers to all the characters in the sequence defined in the square brackets. Option 2 is incorrect. To display a list of files whose names end in 5, 6, 7, or 8, you need to use the ls command with the asterisk (*) wildcard before the sequence defined in the square brackets ([]). The asterisk tells the shell to display only the files defined in the sequence. Option 3 is incorrect. The mv command enables you to move files from one directory to another in a single command line. You use it with square brackets ([]) and the name of the destination directory to specify the range of files you want moved. Option 4 is incorrect. The pwd command instructs the shell to display the path of the current working directory. The square brackets ([]) define a sequence of characters, which isn't appropriate with the pwd command.

2. Invoking commands
When you issue a command in the Linux shell, you are usually invoking an executable file of that name located somewhere in the file system.

Once you've entered a command at the prompt, the Linux kernel searches the directory structure for the relevant file, so that the command can be executed. The PATH environment variable defines which directories the kernel searches for commands. The directories in the PATH variable contain most of the common commands, but they don't contain all of them. You therefore need to follow different procedures when invoking commands located inside and outside the variable. To search for files, you use the find command. This command searches a specified directory, and all subdirectories within it. If no directory is specified, the command utility searches the current working directory first, and then all subdirectories located in that directory. This is the syntax for the find command. find /path expression You can use the find command with these conditions to refine a search:

-atime -ctime -group -newer -name -user

-atime The -atime condition enables you to search based on the number of days since the file was last accessed. -ctime The -ctime condition enables you to search based on the number of days since a directory last changed.
-group

The -group condition enables you to search for files belonging to a specific group. -newer The -newer condition enables you to search for files more recent than a specified file. -name The -name condition searches for files with names that match a specified string. Filename metacharacters may be used, but should be escaped or quoted. -user The -user condition enables you to search for files that belong to a specified user.

Question
Suppose that you know the name of a file but not where it's located in the file system.

Which condition do you use with the find command to locate a file that matches a specific pattern? Options: 1. 2. 3. 4. -atime -ctime -group -name

Answer
You use the -name condition with the find command to find a file if you know the name of the file. Option 1 is incorrect. The -atime condition enables you to search for a file or directory based on the number of days it was last accessed. Option 2 is incorrect. The -ctime condition enables you to search for a file or directory in the file system based on the number of days since the file or directory last changed. Option 3 is incorrect. The -group condition enables you to search for files belonging to a group that you specify. Option 4 is correct. The -name pattern condition with the find command enables you to search for files with names that match the specified pattern. Suppose that you have a program called backup stored in /usr/local/sbin. You want to run the program, but the directory is not specified in the path. To execute the backup command, you need to enter the path to the file at the command prompt.
[root@easynomad1 staff_needs]# cd /usr/local/sbin

If you are already in /usr/local/sbin, you enter the relative path to run the backup. In the code, the period followed by a forward slash (./) refers to the current directory.
[root@easynomad1]# cd /usr/local/sbin [root@easynomad1]# pwd /usr/local/sbin [root@easynomad1]#./backup

Suppose that you're in a different directory for example, /home/grosetti/. To run the program called backup, you therefore need to enter the absolute pathname.
[root@easynomad1]# pwd /home/grosetti [root@easynomad1 grosetti]# /usr/local/sbin/backup

The program called backup executes.


[root@easynomad1 grosetti]# pwd /usr/local/sbin [root@easynomad1 grosetti]# ./backup [root@easynomad1 grosetti]#

For commands that you know are inside the PATH variable, you enter the command name and any relevant options and parameters at the command prompt. However, different versions of a command may be stored in more than one directory in the path. And when Linux searches the path for the command, it automatically runs the first instance of the command that it encounters. You therefore may need to check from which directory a command will be run. If you suspect that the command you want to run is preceded in the path by another command of the same name, you use the which command to display the full location of the version of the command that appears first in the path. To check where the ls command first occurs in the path, for example, you enter the command
which ls [root@easynomad1 grosetti]# which ls

The output of the which command confirms that the first occurrence of the ls command is in the /bin directory.
[root@easynomad1 grosetti]# which ls /bin/ls [root@easynomad1 grosetti]#

To run a different version of the ls command located in /usr/bin, you need to refer to the absolute pathname explicitly when issuing the command. For example, you enter this command.
[root@easynomad1 grosetti]# /bin/ls

The command executes and a list of all the files in the current directory is displayed.
[root@easynomad1 grosetti]# /bin/ls Desktop Documents Meetings Michelle Network past_upgrades staff_needs tmp [root@easynomad1 grosetti]#

3. Using command substitution


When using Linux, you may sometimes want the kernel to perform multiple, related tasks.

Command substitution lets you substitute the results or output of one command for the input of another. So instead of issuing one command and then formulating the syntax of another, related command, you can use command substitution to issue more than one command on the same line. Command substitution is especially useful if you need to write shell scripts.

Note
Shell scripts are executable files that contain multiple Linux-shell commands. Scripts enable you automatically to invoke a sequence of commands just by typing the name of the script at the command prompt. The popular syntax for command substitution is $(command)
[root@easynomad1 grosetti]# ls -l $(which passwd) -r-s--x--x 1 root root 15760 Jul 21 2003 /usr/bin/passwd* [root@easynomad1 grosetti]#

This syntax replaces the previous standard syntax, which surrounded the command with backquotes as in `command `.

Note
Although the output is the same from both forms of syntax, the `command` syntax is less useful because of its potential to deliver incorrect output if it is used to substitute a number of commands on a single command line. Command substitution enables you to create a file and append the date and time to its name in a single command. To create a file called project_team and append the date and time to it, for example, you enter the touch command.
[root@easynomad1 Meetings]# touch project_team$(date +%T-%d_%m_%Y) [root@easynomad1 Meetings]#

The file project_team has now been created in /home/grosetti/Meetings, and the current date and time are appended to the filename. In the command, the touch project_team command created the file named project_team. And the command substitution in the code $(date +%T-%d_%m_%Y) invoked the date command with suitable options to return the time in hours, minutes, and seconds, and the date.

The syntax (command) instructs the shell to execute the contents of the brackets before the touch command, and to append the output to the project_team file. The complete filename, including the actual time and date, is then passed as an option to the touch command. Using command substitution is therefore much easier than consulting the clock and calendar, and typing out the full date and time each time you create a file. To check the command substitution, you enter
ls [root@easynomad1 Meetings]# touch project team$ (date +%T-%d_&m_%Y) [root@easynomad1 Meetings]# ls project_team05:49:59-03_06_2004 [root@easynomad1 Meetings]#

You add the time and date to each new file you create in the directory using the same command substitution syntax. The only part you need to change for example, if you also want to create files named partner, quarterly_meeting, and budgets is the first part of the filename.
[root@easynomad1 Meetings]# touch partners$(date +%T-%d_&m_%Y) [root@easynomad1]# touch quarterly_meetings$(date +%T-%d_% [root@easynomad1]# touch budgets$(date +%T-%d_&m_%Y)

Question
Suppose that you want to append the date and time to a file called project_team. Complete the touch command that will do this in the format time, day, month, and year, with a hyphen after the time and an underscore to delimit the day, month, and year.
[root@easynomad1 Meetings]#touch project_team$ MISSING CODE

Answer
You enter this command to append the date and time to a file called project_team:
touch project_team$(date +%T-%d_%m_%Y)

A simple and powerful alternative method of appending a date and time to a filename is to assign the syntax of the date command to a variable. You can then insert the variable name in the brackets of the $( ) syntax construction, and the shell will interpret it in the same way. To create a new shell variable called "day" with the value of the date syntax you used before, you enter

day="date +%T-%d_%m_%Y"

To check the value of the variable, you then enter


echo $day [root@easynomad1]# day="date +%T-%d_%m_%Y" [root@easynomad1]# echo $day date +%T-%d_%m_%Y [root@easynomad1]#

To create the project_team file with the time and date appended to the filename, you then simply enter
touch project_team$($day) [root@easynomad1]# day="date +%T-%d_%m_%Y" [root@easynomad1]# echo $day date +%T-%d_%m_%Y [root@easynomad1]# touch project_team$($day) [root@easynomad1]#

4. Issuing commands recursively


If you need to perform tasks that relate to an entire directory structure, it's tedious to have to reissue a command for every separate subdirectory in which you need to work. Linux enables you to apply commands recursively through the directory tree. To issue commands recursively, you generally use this syntax. command -r pathname For example, if you want to search quickly for the text string "New Zealand" in all the files in the /home/grosetti/meetings directory and subdirectories, you enter this command.
[root@easynomad1 /]# grep -r "New Zealand" /home/grosetti/Meetings

Once you've entered the grep command, the Linux kernel searches through the directory, and every subsequent subdirectory, for each instance of the requested text.
[root@easynomad1 /]# grep -r "New Zealand" /home/grosetti/Meetings /home/grosetti/Meetings /proposals:Upcoming possibilities - joint-venture with New Zealand firm, showcasing flights and accommodation - Auckland.Systems requirements [root@easynomad1 /]#

Note

The ls command accepts the recursive option in uppercase only that is, -R. Other commands, such as the mv command, which you use to move and rename files, have no recursive option. The -r option enables you to perform a number of tasks for example, copying and deleting files. Suppose that you're logged in as root in the root directory and you enter the command
rm -rf *

This command would cause every file in the file system to be deleted automatically without asking for confirmation. The effect would be to wipe out all your data and your entire operating system.
[root@easynomad1 /]# rm -rf *

You therefore need to take care when issuing these commands especially the rm command with the -r option. Unless you know the exact identity of your present working directory, as well as the content of all its subdirectories, you could accidentally lose valuable files. Aside from being aware of your current working directory, the principal safeguard you can take against losing or overwriting files is to use the -i option for the rm, cp, and mv commands. This option forces the shell to prompt you before a command is executed. For example, the command rm -ir * ensures that you get a second chance to confirm that you want to delete all the files within the current directory, and any subdirectories.
[root@easynomad1 /]# rm -ir * rm: descend into directory `bin'? n rm: descend into directory 'boot'?

Question
Which option or condition do you use with the rm command so that the shell prompts you to confirm the command before executing it? Options: 1. 2. 3. 4. -atime -group
-i -r

Answer
The -i option causes the shell to prompt you for a yes or no response before it executes an rm command.

Option 1 is incorrect. The -atime condition with the find command enables you to search based on the number of days since the file was last accessed. Option 2 is incorrect. The -group condition enables you to search for files belonging to a specific group using the find command. Option 3 is correct. The -i option causes the shell to prompt you for confirmation that you want to execute the rm, mv, or cv commands. Option 4 is incorrect. The -r option enables you to perform tasks such as copying and deleting files.

Summary
In Linux, you can use wildcards to complete or substitute characters within filenames. The three most common wildcards are the asterisk (*), question mark (?), and square brackets ([]). Wildcards save time and assist you in locating specific files and directories. Most commands that you issue are located in the directories specified in the PATH environment variable. When you issue a command that appears in a directory in this variable, Linux executes the first instance of the command that it encounters. To invoke an alternative version of the command from another directory, you need to specify the absolute pathname to the directory when you issue the command. To issue a command and use the result as input for a subsequent command, you use command substitution. The syntax for this is
command1 $(command2)

Command substitution is especially useful when you write shell scripts that include complex or interdependent commands. If you are working with files in a particular directory but don't wish to issue individual commands relating to each one, you can apply certain commands recursively through the directory tree. This means that the command you issue will operate not just on the directory, but also on each subdirectory. When copying or deleting files recursively, you need to be careful not to delete or overwrite files accidentally.

Table of Contents

Working with Linux Commands


Learning objective

After completing this topic, you should be able to use the Linux shell to execute commands and manipulate files.

Exercise overview
In this exercise, you're required to use the Linux shell to execute commands and manipulate files. This involves the following tasks:

editing command history using command substitution

Task 1: Editing command history


Suppose that you are Maria Gomez, a human resources manager for the Easy Nomad travel company. You have recently assumed responsibility for an annual remuneration survey from a colleague. You have just moved several important data files from your current directory to the Remuneration directory.

Step 1 of 4
To begin, you check the contents of the directory you're working in. Which command do you use to list the files in your current directory?
[mgomez@easynomad1] $ MISSING CODEMISSING CODE

Options: 1. 2. 3. 4.
history ls pwd touch

Result
You use the ls command to list the files in the current directory. Option 1 is incorrect. The history command displays all events in the history list. Option 2 is correct. The ls command displays all files in the current working directory. You can use additional parameters with the command to display the contents in different formats, or to include information such as file access times in the output.

Option 3 is incorrect. The pwd command displays the name of the current working directory, rather than its contents. Option 4 is incorrect. The touch command updates the access and modification times for a file. If a file doesn't exist, touch creates a file with a size of 0. You notice that the Statistics.doc file is still in your current directory, although you meant to move it to the Remuneration directory.
[mgomez@easynomad1]$ ls Annual_Taxation_tables Desktop/ Remuneration_policy Data.doc Documents/ Remuneration/ Tax_certificates [mgomez@easynomad1]$ Statistics.doc tmp/

Step 2 of 4
You decide to view the commands you entered most recently to check them. Enter the command that lists only the ten most recently used commands.
[mgomez@easynomad1] $ ls Annual_Taxation_tables Desktop/ Remuneration_policy Data.doc Documents/ Remuneration/ Tax_certificates [mgomez@easynomad1] $ MISSING CODE

Statistics.doc

tmp/

Result
You use the history 10 command and the fc -l -10 command to display the ten most recently used commands. You notice that an mv command was issued to move the Statistics.doc file. You remember now that you'd deleted it in error. And you'd obviously then restored the file to your current directory, instead of moving it to the Remuneration directory.
[mgomez@easynomad1]$ ls Annual_Taxation_tables Desktop/ Remuneration_policy Data.doc Documents/ Remuneration/ Tax_certificates [mgomez@easynomad1]$ history 10 62 history 10 63 mv Statistics.doc ~/mgomez 64 mv Statistics.doc ~/Remuneration 65 pwd 66 mv Statistics.doc ~/Remuneration 67 clear 68 mv Statistics.doc ~/Remuneration 69 clear 70 ls 71 history 10 [mgomez@easynomad1]$ Statistics.doc tmp/

Step 3 of 4
You decide to use a shortcut to reissue the most recently used mv command. Which command do you use?
[mgomez@easynomad1] $ ls Annual_Taxation_tables Desktop/ Remuneration_policy Data.doc Documents/ Remuneration/ Tax_certificates [mgomez@easynomad1] $ history 10 62 history 10 63 mv Statistics.doc ~/mgomez 64 mv Statistics.doc ~/Remuneration 65 pwd 66 mv Statistics.doc ~/Remuneration 67 clear 68 mv Statistics.doc ~/Remuneration 69 clear 70 ls 71 history 10 [mgomez@easynomad1] $ MISSING CODEMISSING CODE

Statistics.doc

tmp/

Options: 1. !mv 2. ?mv 3. mv!

Result
To reissue the most recently issued mv command, you enter !mv. Option 1 is correct. The exclamation mark (!) operator enables you to re-execute previous commands. The appropriate mv command is command number 64 in the history list, so you can enter mv or 64 after the exclamation mark to re-execute the command. Option 2 is incorrect. The question mark (?) symbol is a Linux wildcard operator used in searches. This code would result in a Linux "command not found" error message. Option 3 is incorrect. The exclamation mark (!) operator must appear before the command you want to re-execute. You have now moved the Statistics.doc file to the Remuneration directory.
[mgomez@easynomad1] $ ls Annual_Taxation_tables Desktop/ Remuneration_policy Data.doc Documents/ Remuneration/ Tax_certificates [mgomez@easynomad1] $ history 10 62 history 10 Statistics.doc tmp/

63 mv Statistics.doc ~/mgomez 64 mv Statistics.doc ~/Remuneration 65 pwd 66 mv Statistics.doc ~/Remuneration 67 clear 68 mv Statistics.doc ~/Remuneration 69 clear 70 ls 71 history 10 [mgomez@easynomad1] $ !mv mv Statistics.doc ~/Remuneration [mgomez@easynomad1] $

Step 4 of 4
You notice that the Data.doc file also needs to be moved from your current directory to the Remuneration directory. You decide to use a shortcut to move the file. Which shortcut re-runs the last command you entered but changes the name of the file in the command from Statistics.doc to Data.doc?
[mgomez@easynomad1] $ ls Annual_Taxation_tables Desktop/ Remuneration_policy Data.doc Documents/ Remuneration/ Tax_certificates [mgomez@easynomad1] $ history 10 62 history 10 63 mv Statistics.doc ~/mgomez 64 mv Statistics.doc ~/Remuneration 65 pwd 66 mv Statistics.doc ~/Remuneration 67 clear 68 mv Statistics.doc ~/Remuneration 69 clear 70 ls 71 history 10 [mgomez@easynomad1] $ !mv mv Statistics.doc ~/Remuneration [mgomez@easynomad1] $ MISSING CODE MISSING CODE

Statistics.doc

tmp/

Options: 1. 2. 3. 4.
^Data^Statistics ^mv^Data ^Statistics^Data cp Statistics Data

Result

The ^Statistics^Data command reruns the last command you entered but changes the name of the file in the command from Statistics.doc to Data.doc. Option 1 is incorrect. This code will try to replace "Data" in the re-executing command with "Statistics." It will cause a "substitution failed" error message because the text "Data" does not exist in the previously entered command. Option 2 is incorrect. The mv command is a Linux command for moving files or directories. It cannot be used as the source text in a substitution operation. Option 3 is correct. The substitution operator (^) takes two parameters to enable you to edit a previously entered command. The first parameter is the text to find and replace. The second parameter is the replacement text. Option 4 is incorrect. The cp command is the Linux command to copy files and directories. This code would copy a file called "Statistics" to a file called "Data." You run the ls command to verify that the Data.doc file has been moved from your current directory to the Remuneration directory.
mv Statistics.doc ~/Renumeration [mgomez@easynomad1]$ ^Statistics^Data mv Data.doc ~/Renumeration [mgomez@easynomad1]$ ls Annual_Taxation_tables Documents/ Renumeration/ Desktop/ Renumeration_policy Tax_certificates [mgomez@easynomad1]$

tmp/

Task 2: Using command substitution


Suppose that you are now preparing for an important meeting at which you must present the results of an annual remuneration survey. You want to append the date and time to the names of relevant files in your current directory, so that you can keep track of updates easily.

Step 1 of 2
You decide to use command substitution to append the date and time to a new file called tax_audit in the current directory. Enter the command that will do this in the format time, day, month, and year, with a hyphen between the time and day and an underscore delimiting the day, month, and year.
[mgomez@easynomad1] $ MISSING CODEMISSING CODE

Result
To append the date and time to the new file named tax_audit, you enter the command
touch tax_audit$(date +%T-%d_%m_%Y)

Step 2 of 2
You now want to check that you performed the command substitution correctly. Enter the command that displays the tax_audit file with the date and time appended. Do not include any options with the command.
[mgomez@easynomad1] $ touch tax_audit$(date +%T-%d_%m_%Y) [mgomez@easynomad1] $ MISSING CODEtouch tax_audit$(date +%T-%d_%m_%Y) MISSING CODE

Result
To check the command substitution, you enter ls to list the contents of the current working directory. You have successfully used command substitution to append the date and time to the tax_audit file.
[mgomez@easynomad1] $ touch tax_audit$(date +%T-%d_%m_%Y) [mgomez@easynomad1] $ ls Data.doc Statistics.doc tax_audit09:13:50-07_06_2004 [mgomez@easynomad1]

Table of Contents

Command Redirection in Linux


Learning objective
After completing this topic, you should be able to select the correct command redirection approach offered by Linux.

1. Redirection symbols
Linux defines three standard streams of information standard input (stdin), standard output (stdout), and standard error (stderr).

Generally, standard input comes from your keyboard, and standard output is displayed on your terminal. Errors are directed to the standard error stream, which is also displayed on your terminal. You can redirect command input and output from the standard streams. For example, you can redirect standard output from the terminal to a file, or to another command, which can then use it as input. You can also issue commands that take their input from a file rather than from standard input. Redirecting the output of a command to a file can save time. If a process is taking a long time to run, for example, you can run the process in the background and redirect its output to a file for review when it is finished. You redirect streams using redirection symbols, piping, and some special commands. You can use these redirection symbols:

less than (<) greater than (>) &> or 2>

less than (<) The less than (<) redirection symbol takes standard input from a file you specify. The shell number for standard input is 0. greater than (>) The greater than (>) redirection symbol sends standard output to a file you specify. The shell number for standard output is 1. &> or 2> An ampersand (&) followed by a greater than (>) redirection symbol sends standard error output to a file you specify. The shell number for standard error is 2. You can choose to specify this number instead of an ampersand before the greater than sign to redirect standard error. You can use the greater than (>) symbol to redirect the output of a command to another file, rather than to your display. For example, this command redirects the output of the cat command the contents of the emp_drec and boss_drec files to a file named "overall_drec".
[ksmith@easynomad1]$ cat emp_drec boss_drec > overall_drec

It's important to note that if a file named overall_drec already exists, it will be replaced when you use this command. To append information to an existing file, you use two greater than symbols (>>).
[ksmith@easynomad1]$ cat emp_drec boss_drec >> overall_drec

Errors that occur during this process using an inaccurate filename, for example will be sent to your display and not to the overall_drec file. This command redirects standard output to the overall_drec file and standard error to the file called error_msg.
[ksmith@easynomad1]$ cat emp_drec boss_drec > overall_drec &> error_msg

Instead of the ampersand (&) in the command, you can choose to use the number 2, which is the shell number for standard error.
[ksmith@easynomad1]$ cat emp_drec boss_drec > overall_drec 2> error_msg

To redirect both standard output and standard error using their shell numbers, you enter this command.
[ksmith@easynomad1]$ cat emp_drec boss_drec 1> overall_drec 2> error_msg

A useful way to get rid of error messages is to redirect standard error to the special file /dev/null. When you write to dev/null, it automatically discards the input.
[ksmith@easynomad1]$ cat emp_drec boss_drec > overall_drec 2> /dev/null

To replace an existing file with a null string and still retain its file permissions, you can use this command.
[ksmith@easynomad1]$ cat /dev/null > info_file

Suppose that you want to use input already prepared in a file instead of having to type input on the keyboard. For example, to mail the contents of a file called "info_file" to a user named bob, you enter this command.
[ksmith@easynomad1]$ mail bob < info_file

You should be cautious about redirecting the same file as both input and output to a command, because this may destroy the file's contents.
[ksmith@easynomad1]$ mail bob < info_file

Question
Which statements write the output of the cat command to a file named "overall_drec" replacing the file if it already exists, and route any error messages to a file named "error_msg"? Options: 1. 2. 3. 4.
cat cat cat cat emp_drec emp_drec emp_drec emp_drec boss_drec boss_drec boss_drec boss_drec > overall_drec &> error_msg > overall_drec 2> /dev/null > overall_drec 2> error_msg >> overall_drec 2> error_msg

Answer
This command directs the output of the cat command to a file named overall_drec and writes standard error to a file named error_msg:
$ cat emp_drec boss_drec > overall_drec &> error_msg

In the command, you can choose to replace &> with 2>, because 2 is the shell number for standard error. Option 1 is correct. The greater than sign (>) in the command writes the output of the cat command to the specified overall_drec file. The ampersand followed by a greater than sign (&>) writes standard error to the specified error_msg file. Option 2 is incorrect. This command gets rid of error messages altogether by writing them to the special /dev/null file. Option 3 is correct. The greater than sign (>) in the command writes the output of the cat command to the specified overall_drec file. The 2 followed by a greater than sign writes standard error to the specified error_msg file, in the same way as an ampersand followed by a greater than sign (&>). Option 4 is incorrect. The two greater than signs (>>) in this command append the output of the cat command to the overall_drec file, rather than simply writing its output to the file and replacing any existing content in it.

2. Piping commands
A pipe (|) takes the output of one program or command and connects it to the input of another. Pipes provide an efficient method of connecting several processes. They enable you to enter code more efficiently because they eliminate the need for some intermediate steps in a program.

For example, you want to perform these three functions:


list the content of two files perform a search on the output for the string "This" count the resulting lines

You can perform all three functions in just one line of code by using this syntax. cat newfile newerfile | grep This | wc -l In the syntax, the output of the cat command, which combines two files, is redirected to the grep command. The grep command performs the search for the string "This" on both files. The output of the grep command is then redirected to the wc command, which counts the number of lines in the output from the grep command. If a command's output doesn't fit onto one screen, you can pipe it to a relevant screen reader utility. An example of such a utility is more. Using a pipe in this case makes the output much easier to read.
[ksmith@easynomad1]$ ls -l | more

You can use pipes to sort the output of commands. For example, you want to display an alphabetical listing of all the files in your directory, including hidden files, but you want to ignore the dots (.) preceding hidden files when sorting them. To do this, you use this command. In the command, ls -a produces a list of all the files in your directory, and the pipe redirects the output to a command that sorts it, while ignoring the dots.
ls -a | sort -i

Question
Which command lists the content of two files, performs a search on the output, and then sorts the search results? Options: 1. cat file1 file2 | grep hello | sort -i 2. ls -a | sort -i 3. ls -l | more

Answer
This command lists the content of two files, performs a search on the output, and then sorts the search results:
cat file1 file2 | grep hello | sort -i

Option 1 is correct. The cat command lists the contents of two files, the first pipe symbol redirects the output to a grep command that searches for the string "hello", and the second pipe symbol redirects the search results to the sort command that alphabetizes the output. Option 2 is incorrect. This command displays an alphabetical listing of all files in the directory, including hidden files, but omits the dots (.) preceding hidden files when sorting them. Option 3 is incorrect. This command lists the contents of a directory and then pipes the output to a screen reader utility if it does not fit onto one screen.

3. The xargs command


The xargs command is a more powerful method than piping for sending arguments from one command to another. It lets you repeat a single command for an entire list of arguments, which it reads from an input stream. Usually, these arguments are an extensive list of filenames generated by the find or ls command and passed to xargs via a pipe. You use this syntax with the xargs utility. xargs [options] command[initial arguments] There are several command options you can use with the xargs command. These options let you

insert arguments into the middle of a string echo each execution run a command once for each line of input overcome command-line length limitations

To find the string "xargs help" in a file, for example, you enter this code.
[ksmith@easynomad1]$ find /root -type f -print | xargs grep -n "xargs help"

This find command looks for regular files (-type f) under the root home directory (/root) and prints each filename. This list of files is piped to xargs, which passes each filename in turn to the grep command.

The grep command searches for all occurrences of the string "xargs help" in the files that the find command returns. So each filename that was returned by the find command acts as an argument to the grep command.
[ksmith@easynomad1]$ find /root -type f -print | xargs grep -n "xargs help"

Question
Suppose that you want to find the string "intro one" in any file in the root home directory. Which command do you use to do this? Options: 1. 2. 3. 4.
find find find ls / /root -type /root -type /root -type | xargs grep f -print | sort -i f -print | xargs grep -n "intro one" f | xargs -n "intro one" -n "intro one"

Answer
To find the string "intro one" in any file in the root directory, you use the command:
find /root -type f -print | xargs grep -n "intro one"

Option 1 is incorrect. The find command retrieves and prints the names of files in the root user's home directory. However, the pipe character then redirects this output to a sort operation, rather than to a search operation, and a xargs command hasn't been used to enable the sort operation to act against every file that the find command retrieved. Option 2 is correct. The find command in this case retrieves and prints all regular files under the root user's home directory. The pipe symbol redirects this output to the xargs command, which enables a grep command to search each file in the output for the specified string. Option 3 is incorrect. The find command retrieves and prints the names of regular files in the root's home directory, and the xargs command supplies the output of the command to the command that follows it. However, the code following xargs is missing the grep command, which enables you to search the output for a specified string. So this command will fail. Option 4 is incorrect. This command lists the files in the root directory, rather than the root user's home directory.

4. Tee utility commands

The tee command lets you redirect output to a file, while continuing to display it on the terminal. To use the tee utility, you use this syntax. tee [options] files For example, this command displays a sorted list of files, and saves the list to the file named "AlphaFileList" at the same time.
[ksmith@easynomad1]$ ls -a | sort -i | tee AlphaFileList

The standard output for the tee command can be the display, or you can pipe the output to another command. The tee command overcomes the limitations that arise from redirecting output to a single destination. It also accommodates multiple filenames as arguments, so you can run it against multiple copies of a file. To append the output of the tee command to a specified file, rather than overwriting the file, you use the -a option with the command. For example, to append a sorted list of files to the file named AlphaFileList, you enter this command.
[ksmith@easynomad1]$ ls -a | sort -i | tee -a AlphaFileList

Question
Which command displays a sorted list of files and appends the list to the file named "AlphaFileList" at the same time? Options: 1. ls -a | sort -i < AlphaFileList 2. ls -a | sort -i | tee -a AlphaFileList 3. ls -a | sort -i | tee AlphaFileList

Answer
This command displays a list of sorted files and appends the list to a file named "AlphaFileList" at the same time:
ls -a | sort -i | tee - a AlphaFileList

Option 1 is incorrect. The less than sign (<) instructs this command to use the content of the AlphaFileList file as input, and so would sort and display the information already in the AlphaFileList, rather than saving a separate list of files to it. Option 2 is correct. In this command, the -a option instructs the tee command to append the sorted list of files to the file named "AlphaFileList", rather than overwrite the file. Option 3 is incorrect. In this command, the tee utility displays a sorted list of files and writes, rather than appends, the list to a file named "AlphaFileList".

Summary
Redirection is an essential function of the Linux operating system. The redirection symbols let you redirect standard output, standard input, and standard error to or from a file instead of the terminal or keyboard. For example, output redirection enables you to save output to a file for troubleshooting purposes. The pipe symbol (|) enables you to redirect the output from a command so that it acts as input to another command. The xargs command enables you to run the command that follows it against multiple arguments. Generally, you pipe the output of a previous command to the xargs command to provide this output. The tee command provides standard output at the same time as redirecting output to a file you specify.

Table of Contents

Issuing Redirection Commands in Linux


Learning objective
After completing this topic, you should be able to issue redirection commands to redirect input and output to and from utilities.

Exercise overview
In this exercise, you're required to use redirection commands to redirect input and output. This involves the following task:

issuing redirection commands in Linux

Task 1: Issuing redirection commands


Suppose that you are Kelly Smith, a sales representative for the Easy Nomad travel company. You want to create a text file detailing the company's special offers by entering information in the shell and redirecting it to the file. You then want to add text to the file, view a line count, combine the file with another file, and email the resulting file to another user.

Step 1 of 5
First you want to enter text in the shell and indicate that the output is to be redirected to a file called "special_offers". Which of these commands do you use to do this?
[ksmith@easynomad1] $ MISSING CODE

Options: 1. 2. 3. 4.
cat | special_offers cat < special_offers cat > special_offers echo > special_offers

Result
This command redirects output to the special_offers file:
cat > special_offers

Option 1 is incorrect. The pipe symbol (|) redirects the standard output of the command to the left of the pipe to standard input of the command to the right of the pipe. Option 2 is incorrect. This code uses the incorrect redirection symbol. It will attempt to input special_offers into the cat command. Option 3 is correct. The cat command can concatenate standard user input to user output. The greater than sign (>) is a redirection operator that enables you to redirect output to a file. Option 4 is incorrect. The echo command is used to display a line of text. You can't redirect the output of an echo command to a new file. This command will work only if special_offers is a pre-existing file.

Output will now be redirected to the special_ offers file. You type this code and press Ctrl+D to finish the input session.
[ksmith@easynomad1]$ cat>special_offers Kenyan Safari, August, $ 2500 [ksmith@easynomad1]$

Step 2 of 5
You now want to add a second line reading "Indian tour, July, $3000" to the special_offers file. Which code completes the command to do this?
[ksmith@easynomad1] $ cat > special_offers Kenyan Safari, August, $ 2500 [ksmith@easynomad1] $ echo "Indian Tour, July, \$3000" MISSING CODE

Options: 1. >> special_offers 2. &> special_offers 3. special_offers | sort

Result
The full command for adding the new entry to the special_offers file is
echo "Indian Tour, July, \$3000" >> special_offers

Option 1 is correct. The two greater than signs (>>) followed by a filename instructs the echo command to append information to the specified file. Option 2 is incorrect. The ampersand followed by a greater sign (&>) instructs the command to send standard error to the special_offers file, rather than to append a new entry to the file. Option 3 is incorrect. The | sort command sorts and displays the present content of the file, rather than appending a new entry to it. To check the contents of the new file, you enter a cat command.
[ksmith@easynomad1] $ cat > special_offers Kenyan Safari, August, $ 2500 [ksmith@easynomad1] $ echo "Indian Tour, July, \$3000" >> special_offers [ksmith@easynomad1] cat special_offers

Kenyan Safari, August, $ 2500 Indian Tour, July, $3000 [ksmith@easynomad1]

Step 3 of 5
Now you want to view a line count of the special_offers file using a wc command and direct the output to a new file called "total_offers". Which code completes the command to do this?
[ksmith@easynomad1] $ wc l special_offers MISSING CODE

Options: 1. | tee total_offers 2. >> total_offers 3. grep total_offers file_a

Result
The complete command for counting the lines in the special_offers file and redirecting the output to a file named total_offers is
wc l special_offers| tee total_offers

Option 1 is correct. The pipe character (|) redirects the output of the wc command, which counts the number of lines in the special_offers file, to the tee command. The tee command redirects output to a file named total_offers, as well as continuing to display it on the terminal. Option 2 is incorrect. The two greater than signs (>>) in this code append information to an existing file, rather than redirecting output to a new file named total_offers. Option 3 is incorrect. The grep command would generate a search for the string "total_offers" in a file named "file_a". It would not direct output to a new file. The output confirms that there are two entries in the special_offers file.
[ksmith@easynomad1]$ wc l special_offers| tee total_offers 2 special_offers [ksmith@easynomad1]$

To verify the contents of the new total_offers file, you enter a cat command.
[ksmith@easynomad1] $ wc l special_offers| tee total_offers 2 special_offers [ksmith@easynomad1] $ cat total_offers

And the output of the command confirms that the total_offers file contains the number of lines in the special_offers file.
2 special_offers [ksmith@easynomad1] $

Step 4 of 5
You now want to combine the special_offers and total_offers files into a third file called "offers". You also want to redirect any errors that occur during this process to another file called "errors". Which command do you use to do this?
[ksmith@easynomad1] $ MISSING CODE

Options: 1. cat offers > special_offers total_offers &> errors 2. cat special_offers total_offers > offers 2> errors 3. echo special_offers total_offers > offers 2 > errors

Result
You use this command to combine the two files and to redirect standard error to a file named "errors":
cat special_offers total_offers > offers 2> errors

Option 1 is incorrect. This code will initially look for a file called "offers" and try to send its contents to a file called "special_offers". This will cause an error because the offers file does not yet exist. Option 2 is correct. The cat command can take any number of files as input and concatenate them as one output. In the command, the 2 followed by a greater than sign (2>) redirects standard error to the specified file. Option 3 is incorrect. The echo command displays text, rather than combining files. You can't redirect the output from an echo command to a file. The two files are now combined into a file called "offers" and any errors have been redirected to a file called "errors".
[ksmith@easynomad1]$ cat special_offers total_offers > offers 2> errors [ksmith@easynomad1]$

Step 5 of 5
You now want to e-mail the offers file to Miguel Alvarez, whose e-mail address is malvarez@easynomad.com. Which command do you use to do this?
[ksmith@easynomad1]$ MISSING CODE

Options: 1. $ cat /dev/null > offers 2. mail malvarez@easynomad.com < offers 3. mail offers < malvarez@easynomad.com

Result
To e-mail the offers file to Miguel Alvarez, you use the command:
mail malvarez@easynomad.com < offers

Option 1 is incorrect. This command would replace the offers file with a null string, which discards the input but retains file permissions. Option 2 is correct. Because standard input is redirected by the less than (<) symbol, you can use input already prepared in a file and combine it with the mail command to mail it to another user. Option 3 is incorrect. This code is not valid. The shell would interpret the command as an instruction to mail the malvarez@easynomad.com file to the e-mail address "offers", which is impossible. You have now e-mailed the file to Miguel Alvarez.
[ksmith@easynomad1]$ mail malvarez@easynomad.com < offers [ksmith@easynomad1]$

| Print | Contents |

Introduction to Linux processes


Abstract
This article defines the role of a process in Linux and illustrates process control using the ps, bg, and fg commands. The ps command displays information on processes running under the shell.

The bg command enables you to place a process in the background, and the fg command places a process in the foreground.

Introduction
A process is a single program that is executed within its own virtual address space. For example, a shell is a process that is created each time a user logs in to the system. It creates a new process every time it implements a program such as a system command. A system command is an example of a collection of related commands called a job. Jobs create a series of separate processes from a single command line. So, in fact, every program running under Linux is a process. The following table shows the three main categories of processes.
Categories of processes Process type Description

Interactive A foreground or background process initiated from and controlled by the shell Batch Daemon A process that is one of a series of processes in a queue executed sequentially A process usually initiated at boot time and that runs in the background until it's requested a good example is the init daemon

Linux can share its processing power, storage capabilities, and input and output mechanisms with several users, or with several processes created by one user. Processes such as user jobs, operating system tasks, mail, and background jobs like printing need to be monitored simultaneously by Linux.

PIDs
When a request is made to the shell, it assigns a specific identity number called a process identifier (PID) to the corresponding process. PIDs enable the shell to identify the process it's working on and helps it to monitor the progress of this process. PIDs start at zero, beginning at boot time, and increase by one for each process being run. Once the highest system-determined number has been reached, such as 65,564, the procedure starts from zero again, skipping the PIDs for processes that are still active. Every new command creates at least one extra process. For example, to print a file called report.txt, you enter
$ lp report.txt

This creates an extra process lp on top of the already existing shell process that is running in the foreground. So the shell prompt reappears onscreen only after the lp command is finished, because only one process can occupy the foreground at any one time.

Parent and child processes


Each existing process becomes a parent process when it initiates a new process. The new process is referred to as a child process. For example, say you run a shell script called shellscript1 that contains an ls command. The shell executes a process called shellscript1, which in turn generates a process called ls. So the shell process becomes the parent of shellscript1, and shellscript1 then becomes the parent of ls. A parent process bestows its environment upon the child process. A child process will include standard input (stdin), standard output (stdout), and standard error (stderr). So if you open a file in a shell script (its parent), the commands that follow in the script will retain the open file in their environment. However, the parent and child processes will remain unaffected by any changes in the environment that occur during the execution of a process. This is because the processes run independently of each other. Therefore, after the child process has been initiated, any files opened in either the parent or the child will not be available to the other process.

Using the ps command


You use the ps command to identify which processes are currently running in the system. It helps you to monitor the process running in the foreground, and allows you, as root, to see what other processes are running. To list all current processes running under a User ID (UID), you type ps without using options or arguments. This returns the PIDs of the processes, the terminal they originated from, their current status, the CPU time used, and the command running in the processes. For example, the command could return output such as
$ ps PID TTY TIME CMD 511 tty1 00:00:00 login 7062 tty1 02:34:59 bash 17079 tty1 00:00:00 ps

This output shows that the user's startup shell is bash (PID 7062). The startup shell sometimes has a hyphen placed before it to differentiate it from any shells started afterwards. But some versions of the ps command don't do this. General users can display their own processes only using the ps command. However, superusers can use the ps command to list every process running in the system. There are many complex options for the ps command. Some options determine the sets of processes to be produced, whereas others determine the output format. Some options are

preceded by a dash () in the traditional Linux manner, but others are not. And sometimes the same letter produces completely different output depending on whether it has a dash or not. For instance, $ ps -a produces a full listing of all processes, but $ ps a produces a modified listing of all the processes in the current terminal. For a full listing of the different ps options, you can consult the man pages for ps. For most purposes, a simple set of common options for the ps command provide sufficient power and flexibility. The -a option provides a listing of all processes currently running on all the terminals. The listing below shows the processes running under tty1 and tty2, for example:
$ ps a PID TTY TIME CMD 7062 tty1 02:34:5 bash 16894 tty2 00:00:00 bash 16906 tty2 00:00:00 startx 16913 tty2 00:00:00 xinit 16917 tty2 00:00:00 gnome-session 16927 tty2 00:00:00 gnome-smproxy 16933 tty2 00:00:00 enlightenment 16952 tty2 00:00:00 magicdev 16969 tty2 00:00:00 panel 16971 tty2 00:00:00 gmc 16988 tty1 00:00:00 ps

The f option, without a dash, uses ASCII characters to graphically represent a hierarchical view of the parent-child relationships between processes. This is particularly useful if you're considering killing processes, because it helps you ensure that you don't kill a child process accidentally when you kill a parent process. In the listing below, process 16906 is the parent of 16913, which in turn is the parent of 16917:
$ ps f a PID TTY STAT TIME COMMAND 16894 tty2 S 0:00 -bash 16906 tty2 S 0:00 sh /usr/X11R6/bin/startx 16913 tty2 S 0:00 \_ xinit /etc/X11/xinit/xinitrc -- :0 auth /root/.X 16917 tty2 S 0:00 \_ /usr/bin/gnome-session 7062 tty1 S 154:59 -bash 17105 tty1 R 0:00 ps f a 16971 tty2 S 0:00 gmc --sm-client-id default10 16969 tty2 S 0:00 panel --sm-client-id default8 16952 tty2 S 0:00 magicdev --sm-client-id=default12 16933 tty2 S 0:00 enlightenment clientId default2 16927 tty2 S 0:00 gnome-smproxy --sm-client-id default

Using the -l option with the ps command shows more detailed information in the process entry. This includes the parent PID (PPID), the size, the UID, the status, and the priority of a process. For example, the ps -l command might return output such as
$ ps l F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD 100 S 0 511 1 0 60 0 549 wait4 tty1 00:00:00 login

100 S 0 7062 511 0 70 0 808 wait4 tty1 02:34:59 bash 100 R 0 17115 7062 0 73 0 627 tty1 00:00:00 ps

The PPID column shows the process that started each process. This is useful if you need to identify child processes.

Background and foreground processes


An interactive process can run in the foreground or background. To place a process in the background, you use the command bg or the ampersand symbol (&). This lets you do other jobs while waiting for the command to finish. Suppose that you use the syntax: $ find / filename 2> /dev/null | grep filename | tee result A command using this syntax could take a long time to execute, especially if you have a lot of files and are listing several network drives. Only one job at a time can run in the foreground, so no further commands can be issued until the prompt returns. To continue working on the command line while it processes, you can execute the same command in the background, using the ampersand. For example, you could enter the command using the following syntax: $ find / filename 2> /dev/null | grep filename >result & After the command has been issued, the shell displays a message, which looks similar to this:
$ find / filename 2> /dev/null | grep filename >result & [1] 60913 $

The number after the brackets, 60913, indicates the PID for the process, so the status of the background command can be monitored. You can run numerous commands in the background simultaneously. When the background command has been completed, you will see a line like this:
[1]+ Done find / filename 2> /dev/null | grep filename >result

Note that the output of a long job has to be redirected when it's placed in the background. This prevents difficulties when you use the command prompt, because otherwise the output from the background command would continue to appear as you typed. You use the bg command to send a command to the background while it is running. Initially, you press Ctrl+Z to stop the process, and then enter the bg command to place it in the background, where it resumes execution. Placing a process in the background clears the system, leaving the command line available for other uses.

If it is an interactive process, a message like this will occasionally appear:


[1]+ Stopped (tty output) telnet localhost

If a command is stopped, you can start it running again in the background using the bg command as in
$ bg %1

To maintain control of the command and to return it to the foreground, you enter a percent symbol (%) before the command's job number. You then use the fg command to return the process to the foreground, as in the following example:
$ fg %1

Summary
Processes perform tasks specified at the command line in Linux. Each process can initiate other processes. Process identity numbers (PIDs) let the shell keep track of which particular process it's working on. The ps command displays information about each of the processes running under the shell. The bg command enables you to place a process in the background, so that you can do other jobs while waiting for the command to finish. A PID preceded by a percent symbol (%) and used with the fg command returns a process to the foreground.

Table of Contents
| Introduction | | PIDs | | Parent and child processes | | Using the ps command | | Background and foreground processes | Copyright 2008 SkillSoft. All rights reserved. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries.

You might also like