Chapter 18. Working with the Shell

Contents

18.1. Getting Started with the Bash Shell
18.2. Users and Access Permissions
18.3. Important Linux Commands
18.4. The vi Editor

Abstract

When booting your Linux system, you are usually directed to a graphical user interface that guides you through the login process and the following interactions with the system. Although graphical user interfaces have become very important and user-friendly, using them is not the only way to communicate with your system. You can also use a text-oriented communication like a command line interpreter, usually called the shell, where you can enter commands. Because Linux provides options to start shell windows from the graphical user interface, you can easily use both methods.

In administration, shell-based applications are especially important for controlling computers over slow network links or if you want to perform tasks as root on the command line. For Linux newbies it might be rather unusual to enter commands in a shell, but you will soon realize that the shell is not only for administrators—in fact, using the shell is often the quickest and easiest way to perform some daily tasks.

There are several shells for UNIX or Linux. The default shell in SUSE® Linux Enterprise is Bash (GNU Bourne-Again Shell).

This chapter deals with a couple of basics you need to know for using the shell. This includes the following topics: how to enter commands, the directory structure of Linux, how to work with files and directories and how to use some basic functions, the user and permission concept of Linux, an overview of important shell commands, and a short introduction to the vi editor, which is a default editor always available in Unix and Linux systems.

18.1. Getting Started with the Bash Shell

In Linux, you can use the command line parallel to the graphical user interface and easily switch between them. To start a terminal window from the graphical user interface in KDE, click the Konsole icon in the panel. In GNOME, click the GNOME Terminal icon in the panel.

The Konsole or the GNOME Terminal window appears, showing the prompt on the first line like in Figure 18.1, “Example of a Bash Terminal Window”. The prompt usually shows your login name (in this example, tux), the hostname of your computer (here, knox), and the current path (in this case, your home directory, indicated by the tilde symbol, ~). When you are logged in on a remote computer this information always shows you which system you are currently working on. When the cursor is after this prompt, you can send commands directly to your computer system.

Figure 18.1. Example of a Bash Terminal Window

Example of a Bash Terminal Window

18.1.1. Entering Commands

A command consists of several elements. The first element is always the actual command, followed by parameters or options. You can type a command and edit it by using , , <—, Del, and Space. You can also add options or correct typing errors. The command is executed when you press Enter.

[Important]No News Is Good News

The shell is not verbose: in contrast to some graphical user interfaces, it usually does not provide confirmation messages when commands have been executed. Messages only appear in case of problems or errors.

Also keep this in mind for commands to delete objects. Before entering a command like rm for removing a file, you should know if you really want to get rid of the object: it will be deleted irretrievably, without enquiry.

18.1.1.1. Using Commands without Options

Look at the structure of commands using a simple example: the ls command, used to list the contents of a directory. The command can be used with or without options. Entering the plain ls command shows the contents of the current directory:

Figure 18.2. The ls Command

The ls Command

Unlike in other operating systems, files in Linux may have a file extension, such as .txt, but do not need to have one. This makes it difficult to differentiate between files and folders in this output of the ls. By default, the colors can give you a hint: directories are usually shown in blue, files in black.

18.1.1.2. Using Commands with Options

A better way to get more details about the contents of a directory is using the ls command with a string of options. Options modify the way a command works so that you can get it to do specific tasks. Options are separated from the command with a blank and are prefixed with a hyphen. The ls -l command shows the contents of the same directory in full detail (long listing format):

Figure 18.3. The ls -l Command

The ls -l Command

On the left of each object name, information about the object is shown in several columns. The most important are the following: The first column shows the file type of the object (in this example, d for directory or - for normal files). The next nine columns show the user permissions for the object. Columns 11 and 12 show the name of the file owner and the group (in this case, tux and users). Find information about user permissions and the user concept of Linux in Section 18.2, “Users and Access Permissions”. The next column shows the file size in bytes. Then date and time of the last change are displayed. The last column shows the object name.

If you want to see even more, you can combine two options for the ls command and enter ls -la. The shell now also shows hidden files in the directory, indicated by a dot in front (for example, .hiddenfile).

18.1.1.3. Getting Help

Nobody is expected to know all options of all commands by heart. If you remember the command name but are not sure about the options, you can enter the command followed by a blank and --help. This --help option exists for many commands. Entering ls --help displays all the options for the ls command.

18.1.2. Linux Directory Structure

Because the shell does not offer a graphical overview of directories and files like the tree view in a file manager, it is useful to have some basic knowlegde of the default directory structure in a Linux system. You can think of directories as electronic folders in which files, programs, and subdirectories are stored. The top level directory in the hierarchy is the root directory, referred to as /. This is the place from which all other directories can be accessed.

Figure 18.4 shows the standard directory tree in Linux, with the home directories of the example users yxz, linux, and tux. The /home directory contains the directories in which the individual users can store their personal files.

[Note]Home Directory in a Network Environment

If you are working in a network environment, your home directory may not be called /home. It can be mapped to any directory in the file system.

The following list provides a brief description of the standard directories in Linux.

Figure 18.4. Excerpt from a Standard Directory Tree

Excerpt from a Standard Directory Tree

Table 18.1. Overview of a Standard Directory Tree

/

Root directory, starting point of the directory tree

/home

Personal directories of users

/dev

Device files that represent hardware components

/etc

Important files for system configuration

/etc/init.d

Boot scripts

/bin, /sbin

Programs needed early in the boot process (/bin) and for the administrator (/sbin)

/usr, /usr/local

All application programs and local, distribution-independent extensions (/usr/local)

/usr/bin, /usr/sbin

Generally accessible programs (/usr/bin) and reserved for the system administrator ( /usr/sbin)

/usr/share/doc

Various documentation files

/tmp, /var/tmp

Temporary files (do not save files in this directory unless you do not need them)

/opt

Optional software, larger add-on program packages (such as KDE, GNOME, and Netscape)

/proc

Process file system

/sys

System file system where all device information for the kernel is gathered

/var/log

System log files


18.1.3. Working with Directories and Files

To address a certain file or directory, you must specify the path leading to that directory or file. There are two ways to specify a path:

  • The entire (absolute) path from the root directory to the respective file

  • A path starting from the current directory (relative path)

Absolute paths always start with a slash. Relative paths do not have a slash at the beginning.

[Note]Linux Is Case-Sensitive

Linux distinguishes between uppercase and lowercase in the file system. For example, entering test.txt or Test.txt makes a difference in Linux. Keep this in mind when entering filenames or paths.

To change directories, use the cd command.

  • To switch to your home directory, enter cd.

  • Refer to the current directory with a dot (.). This is mainly useful for other commands (cp, mv, …).

  • The next higher level in the tree is represented by two dots (..). For example, to switch to the parent directory of your current directory, enter cd ...

18.1.3.1. Examples of Addressing a File

The cd commands in Section 18.1.3, “Working with Directories and Files” used relative paths. You can use also absolute paths. For example, suppose you want to copy a file from your home directory to a subdirectory of /tmp:

  1. First, from your home directory create a subdirectory in /tmp:

    1. If your current directory is not your home directory, enter cd ~ to switch to it. From anywhere in the file system, you can reach your home directory by entering cd ~.

    2. In your home directory, enter mkdir /tmp/test. mkdir stands for make directory. This command creates a new directory named test in the /tmp directory. In this case, use an absolute path to create the directory.

    3. To check what happened, now enter ls -l /tmp. The new directory test should appear in the list of contents of the /tmp directory.

  2. Now create a new file in your home directory and copy it to the /tmp/test directory by using a relative path.

    1. Enter touch myfile.txt. The touch command with the myfile.txt option creates a new, empty file named myfile.txt in your current directory.

    2. Check this by entering ls -l. The new file should appear in the list of contents.

    3. Enter cp myfile.txt ../tmp/test. This copies myfile.txt to the directory /tmp/test without changing the name of the file.

    4. Check this by entering ls -l /tmp/test. The file myfile.txt should appear in the list of contents for /tmp/test.

To list the contents of home directories of other users, enter ls ~username . In the example directory tree in Figure 18.4, “Excerpt from a Standard Directory Tree”, one of the sample users is tux. In this case, ls ~tux would list the contents of the home directory of tux.

[Note]Handling Blanks in Filenames or Directory Names

If a filename contains a space, either escape the space using a back slash (\) in front of the blank or enclose the filename in single or double quotes. Otherwise Bash interprets a filename like My Documents as the names of two files or directories. The difference between single and double quotes is that variable expansion takes place within double quotes. Single quotes ensure that the shell sees the quoted string literally.

18.1.4. Useful Features of the Shell

Entering commands in Bash can include a lot of typing. In the following, get to know some features of the Bash that can make your work a lot easier and save a lot of typing.

18.1.4.1. History and Completion

By default, Bash remembers commands you have entered. This feature is called history. To repeat a command that has been entered before, press until the desired command appears at the prompt. Press to move forward through the list of previously entered commands. Use Ctrl+R to search in the history.

You can edit the selected command, for example, changing the name of a file, before you execute the command by pressing Enter. To edit the command line, just move the cursor to the desired position using the arrow keys and start typing.

Completing a filename or directory name to its full length after typing its first letters is another helpful feature of Bash. To do so, type the first letters then press →|. If the filename or path can be uniquely identified, it is completed at once and the cursor moves to the end of the filename. You can then enter the next option of the command, if necessary. If the filename or path cannot be uniquely identified (because there are several filenames starting with the same letters), the filename or path is only completed up to the point where again several options are possible. You can then obtain a list of them by pressing →| a second time. After this, you can enter the next letters of the file or path then try completion again by pressing →|. When completing filenames and paths with the help of →|, you can simultaneously check whether the file or path you want to enter really exists (and you can be sure of getting the spelling right).

18.1.4.2. Wild Cards

Another convenience offered by the shell is wild cards for pathname expansion. Wild cards are characters that can stand for other characters. There are three different types of these in Bash:

?

Matches exactly one arbitrary character

*

Matches any number of characters

[set]

Matches one of the characters from the group specified inside the square brackets, which is represented here by the string set. As part of set you can also specify character classes using the syntax [:class:], where a class is one of alnum, alpha, ascii, etc.

Using ! or ^ at the beginning of the group ([!set]) matches one character other than those identified by set.

Assuming that your test directory contains the files Testfile, Testfile1, Testfile2, and datafile.

  • The command ls Testfile? lists the files Testfile1 and Testfile2.

  • The command ls Testfile? lists the files Testfile1 and Testfile2.

  • With ls Test*, the list also includes Testfile.

  • The command ls *fil* shows all the sample files.

  • Use the set wild card to address all sample files whose last character is a number: ls Testfile[1-9] or, using classes, ls Testfile[[:digit:]].

Of the four types of wild cards, the most inclusive one is the asterisk. It could be used to copy all files contained in one directory to another one or to delete all files with one command. The command rm *fil*, for instance, would delete all files in the current directory whose name includes the string fil.

18.1.4.3. Viewing Files with Less and More

Linux includes two small programs for viewing text files directly in the shell: less and more. Rather than starting an editor to read a file like Readme.txt, simply enter less Readme.txt to display the text in the console window. Use Space to scroll down one page. Use Page Up and Page Down to move forward or backward in the text. To exit less, press Q.

Instead of less, you can also use the older program more. However, it is less convenient because it does not allow you to scroll backwards.

The program less got its name from the the precept that less is more and can also be used to view the output of commands in a convenient way. To see how this works, read Section 18.1.4.4, “Redirection and Pipes”.

18.1.4.4. Redirection and Pipes

Normally, the standard output in the shell is your screen or the console window and the standard input is the keyboard. However, the shell provides functions by which you can redirect the input or the output to another object, such as a file or another command. With the help of the symbols > and <, for example, you can forward the output of a command to a file (output redirection) or use a file as input for a command (input redirection). For example, if you want to write the output of a command such as ls to a file, enter ls -l > file.txt. This creates a file named file.txt that contains the list of contents of your current directory as generated by the ls command. However, if a file named file.txt already exists, this command overwrites the existing file. To prevent this, use >>. Entering ls -l >> file.txt simply appends the output of the ls command to an already existing file named file.txt. If the file does not exist, it is created.

Sometimes it is also useful to use a file as the input for a command. For example, with the tr command, you can replace characters redirected from a file and write the result to the standard output, your screen. Suppose you want to replace all characters t of your file.txt from the example above with x and print this to your screen. Do so by entering tr t x < file.txt.

Just like the standard output, the standard error output is sent to the console. To redirect the standard error output to a file named errors, append 2> errors to the corresponding command. Both standard output and standard error are saved to one file named alloutput if you append >& alloutput.

Using pipelines or pipes is also a sort redirection, although the use of the pipe is not constrained to files. With a pipe (|), you can combine several commands, using the output of one command as input for the next command. For example, to view the contents or your current directory in less, enter ls | less. This only makes sense if the normal output with ls would be too lengthy. For instance, if you view the contents of the dev directory with ls /dev, you only see a small portion in the window. View the entire list with ls /dev | less.

18.1.5. Archives and Data Compression

Now that you have already created a number of files and directories, consider the subject of archives and data compression. Suppose you want to have the entire test directory packed in one file that you can save on a USB stick as a backup copy or send by e-mail. To do so, use the command tar (for tape archiver). With tar --help, view all the options for the tar command. The most important of these options are explained here:

-c

(for create) Create a new archive.

-t

(for table) Display the contents of an archive.

-x

(for extract) Unpack the archive.

-v

(for verbose) Show all files on screen while creating the archive.

-f

(for file) Choose a filename for the archive file. When creating an archive, this option must always be given as the last one.

To pack the test directory with all its files and subdirectories into an archive named testarchive.tar, do the following:

  1. Open a shell.

  2. Use cd to your home directory where the test directory is located.

  3. Enter tar -cvf testarchive.tar test. The -c option creates the archive, making it a file as directed by -f. The -v option lists the files as they are processed.

  4. View the contents of the archive file with tar -tf testarchive.tar.

The test directory with all its files and directories has remained unchanged on your hard disk. To unpack the archive, enter tar -xvf testarchive.tar, but do not try this yet.

For file compression, the obvious choice is gzip or, for a even better compression ratio, bzip2. Just enter gzip testarchive.tar (or bzip2 testarchive.tar, but gzip is used in this example). With ls, now see that the file testarchive.tar is no longer there and that the file testarchive.tar.gz has been created instead. This file is much smaller and therefore much better suited for transfer via e-mail or storage on a USB stick.

Now, unpack this file in the test2 directory created earlier. To do so, enter cp testarchive.tar.gz test2 to copy the file to that directory. Change to the directory with cd test2. A compressed archive with the .tar.gz extension can be unzipped with the gunzip command. Enter gunzip testarchive.tar.gz, which results in the file testarchive.tar, which then needs to be extracted or untarred with tar -xvf testarchive.tar. You can also unzip and extract a compressed archive in one step with tar -xvf testarchive.tar.gz (adding the -z option is no longer required). With ls, you can see that a new test directory has been created with the same contents as your test directory in your home directory.

18.1.6. Cleaning Up

After this crash course, you should be familiar with the basics of the Linux shell or command line. You may want to clean up your home directory by deleting the various test files and directories using the rm and rmdir commands. In Section 18.3, “Important Linux Commands”, find a list of the most important commands and a brief description of their functions.

18.2. Users and Access Permissions

Since its inception in the early 1990s, Linux has been developed as a multiuser system. Any number of users can work on it simultaneously. Users need to log in to the system before starting a session at their workstations. Each user has a username with a corresponding password. This differentiation of users guarantees that unauthorized users cannot see files for which they do not have permission. Larger changes to the system, such as installing new programs, are also usually impossible or restricted for normal users. Only the root user, or super user, has the unrestricted capacity to make changes to the system and unlimited access to all files. Those who use this concept wisely, only logging in with full root access when necessary, can cut back the risk of unintentional loss of data. Because under normal circumstances only root can delete system files or format hard disks, the threat from the Trojan horse effect or from accidentally entering destructive commands can be significantly reduced.

18.2.1. File System Permissions

Basically, every file in a Linux file system belongs to a user and a group. Both of these proprietary groups and all others can be authorized to write, read, or execute these files.

A group, in this case, can be defined as a set of connected users with certain collective rights. For example, call a group working on a certain project project3. Every user in a Linux system is a member of at least one proprietary group, normally users. There can be as many groups in a system as needed, but only root is able to add groups. Every user can find out, with the command groups, of which groups he is a member.

File Access

The organization of permissions in the file system differs for files and directories. File permission information can be displayed with the command ls -l. The output could appear as in Example 18.1, “Sample Output Showing File Permissions”.

Example 18.1. Sample Output Showing File Permissions

-rw-r----- 1 tux project3 14197 Jun 21  15:03 Roadmap

As shown in the third column, this file belongs to user tux. It is assigned to the group project3. To discover the user permissions of the Roadmap file, the first column must be examined more closely.

-

rw-

r--

---

Type

Users Permissions

Group Permissions

Permissions for Other Users

This column consists of one leading character followed by nine characters grouped in threes. The first of the ten letters stands for the type of file system component. The hyphen () shows that this is a file. A directory (d), a link (l), a block device (b), or a character device could also be indicated.

The next three blocks follow a standard pattern. The first three characters refer to whether the file is readable (r) or not (). A w in the middle portion symbolizes that the corresponding object can be edited and a hyphen () means it is not possible to write to the file. An x in the third position denotes that the object can be executed. Because the file in this example is a text file and not one that is executable, executable access for this particular file is not needed.

In this example, tux has, as owner of the file Roadmap, read (r) and write access (w) to it, but cannot execute it (x). The members of the group project3 can read the file, but they cannot modify it or execute it. Other users do not have any access to this file. Other permissions can be assigned by means of ACLs (access control lists).

Directory Permissions

Access permissions for directories have the type d. For directories, the individual permissions have a slightly different meaning.

Example 18.2. Sample Output Showing Directory Permissions

drwxrwxr-x 1 tux project3 35 Jun 21 15:15  ProjectData

In Example 18.2, “Sample Output Showing Directory Permissions”, the owner (tux) and the owning group (project3) of the directory ProjectData are easy to recognize. In contrast to the file access permissions from File Access , the set reading permission (r) means that the contents of the directory can be shown. The write permission (w) means that new files can be created. The executable permission (x) means that the user can change to this directory. In the above example, the user tux as well as the members of the group project3 can change to the ProjectData directory (x), view the contents (r), and add or delete files (w). The rest of the users, on the other hand, are given less access. They may enter the directory (x) and browse through it (r), but not insert any new files (w).

18.2.2. Modifying File Permissions

Changing Access Permissions

The access permissions of a file or directory can be changed by the owner and, of course, by root with the command chmod followed by the parameters changing the permissions and one or more filenames. The parameters form different categories:

  1. Users concerned

    • u (user)—owner of the file

    • g (group)—group that owns the file

    • o (others)—additional users (if no parameter is given, the changes apply to all categories)

  2. A character for deletion (), setting (=), or insertion (+)

  3. The abbreviations

    • rread

    • wwrite

    • xexecute

  4. Filename or filenames separated by spaces

If, for example, the user tux in Example 18.2, “Sample Output Showing Directory Permissions” also wants to grant other users write (w) access to the directory ProjectData, he can do this using the command chmod o+w ProjectData.

If, however, he wants to deny all users other than himself write permissions, he can do this by entering the command chmod go-w ProjectData. To prohibit all users from adding a new file to the folder ProjectData, enter chmod -w ProjectData. Now, not even the owner can create a new file in the directory without first reestablishing write permissions.

Changing Ownership Permissions

Other important commands to control the ownership and permissions of the file system components are chown (change owner) and chgrp (change group). The command chown can be used to transfer ownership of a file to another user. However, only root is permitted to perform this change.

Suppose the file Roadmap from Example 18.2, “Sample Output Showing Directory Permissions” should no longer belong to tux, but to the user geeko. root should then enter chown geeko Roadmap.

chgrp changes the group ownership of the file. However, the owner of the file must be a member of the new group. In this way, the user tux from Example 18.1, “Sample Output Showing File Permissions” can switch the group owning the file ProjectData to project4 with the command chgrp project4 ProjectData, as long as he is a member of this new group.

18.3. Important Linux Commands

This section gives insight into the most important commands. There are many more commands than listed in this chapter. Along with the individual commands, parameters are listed and, where appropriate, a typical sample application is introduced. To learn more about the various commands, use the manual pages, accessed with man followed by the name of the command, for example, man ls.

In the man pages, move up and down with PgUp and PgDn. Move between the beginning and the end of a document with Home and End. End this viewing mode by pressing Q. Learn more about the man command itself with man man.

In the following overview, the individual command elements are written in different typefaces. The actual command and its mandatory options are always printed as command option. Specifications or parameters that are not required are placed in [square brackets].

Adjust the settings to your needs. It makes no sense to write ls file if no file named file actually exists. You can usually combine several parameters, for example, by writing ls -la instead of ls -l -a.

18.3.1. File Commands

The following section lists the most important commands for file management. It covers anything from general file administration to manipulation of file system ACLs.

18.3.1.1. File Administration

ls [options] [files]

If you run ls without any additional parameters, the program lists the contents of the current directory in short form.

-l

Detailed list

-a

Displays hidden files

cp [options] source target

Copies source to target.

-i

Waits for confirmation, if necessary, before an existing target is overwritten

-r

Copies recursively (includes subdirectories)

mv [options] source target

Copies source to target then deletes the original source.

-b

Creates a backup copy of the source before moving

-i

Waits for confirmation, if necessary, before an existing targetfile is overwritten

rm [options] files

Removes the specified files from the file system. Directories are not removed by rm unless the option -r is used.

-r

Deletes any existing subdirectories

-i

Waits for confirmation before deleting each file

ln [options] source target

Creates an internal link from source to target. Normally, such a link points directly to source on the same file system. However, if ln is executed with the -s option, it creates a symbolic link that only points to the directory in which source is located, enabling linking across file systems.

-s

Creates a symbolic link

cd [options] [directory]

Changes the current directory. cd without any parameters changes to the user's home directory.

mkdir [options] directory

Creates a new directory.

rmdir [options] directory

Deletes the specified directory if it is already empty.

chown [options] username[:[group]] files

Transfers ownership of a file to the user with the specified username.

-R

Changes files and directories in all subdirectories

chgrp [options] groupname files

Transfers the group ownership of a given file to the group with the specified group name. The file owner can only change group ownership if a member of both the current and the new group.

chmod [options] mode files

Changes the access permissions.

The mode parameter has three parts: group, access, and access type. group accepts the following characters:

u

User

g

Group

o

Others

For access, grant access with + and deny it with -.

The access type is controlled by the following options:

r

Read

w

Write

x

Execute—executing files or changing to the directory

s

Setuid bit—the application or program is started as if it were started by the owner of the file

As an alternative, a numeric code can be used. The four digits of this code are composed of the sum of the values 4, 2, and 1—the decimal result of a binary mask. The first digit sets the set user ID (SUID) (4), the set group ID (2), and the sticky (1) bits. The second digit defines the permissions of the owner of the file. The third digit defines the permissions of the group members and the last digit sets the permissions for all other users. The read permission is set with 4, the write permission with 2, and the permission for executing a file is set with 1. The owner of a file would usually receive a 6 or a 7 for executable files.

gzip [parameters] files

This program compresses the contents of files using complex mathematical algorithms. Files compressed in this way are given the extension .gz and need to be uncompressed before they can be used. To compress several files or even entire directories, use the tar command.

-d

Decompresses the packed gzip files so they return to their original size and can be processed normally (like the command gunzip)

tar options archive files

tar puts one or more files into an archive. Compression is optional. tar is a quite complex command with a number of options available. The most frequently used options are:

-f

Writes the output to a file and not to the screen as is usually the case

-c

Creates a new tar archive

-r

Adds files to an existing archive

-t

Outputs the contents of an archive

-u

Adds files, but only if they are newer than the files already contained in the archive

-x

Unpacks files from an archive (extraction)

-z

Packs the resulting archive with gzip

-j

Compresses the resulting archive with bzip2

-v

Lists files processed

The archive files created by tar end with .tar. If the tar archive was also compressed using gzip, the ending is .tgz or .tar.gz. If it was compressed using bzip2, the ending is .tar.bz2.

locate patterns

This command is only available if you have installed the findutils-locate package. The locate command can find in which directory a specified file is located. If desired, use wild cards to specify filenames. The program is very speedy, because it uses a database specifically created for the purpose (rather than searching through the entire file system). This very fact, however, also results in a major drawback: locate is unable to find any files created after the latest update of its database. The database can be generated by root with updatedb.

updatedb [options]

This command performs an update of the database used by locate. To include files in all existing directories, run the program as root. It also makes sense to place it in the background by appending an ampersand (&), so you can immediately continue working on the same command line (updatedb &). This command usually runs as a daily cron job (see cron.daily).

find [options]

With find, search for a file in a given directory. The first argument specifies the directory in which to start the search. The option -name must be followed by a search string, which may also include wild cards. Unlike locate, which uses a database, find scans the actual directory.

18.3.1.2. Commands to Access File Contents

file [options] [files]

With file, detect the contents of the specified files.

-z

Tries to look inside compressed files

cat [options] files

The cat command displays the contents of a file, printing the entire contents to the screen without interruption.

-n

Numbers the output on the left margin

less [options] files

This command can be used to browse the contents of the specified file. Scroll half a screen page up or down with PgUp and PgDn or a full screen page down with Space. Jump to the beginning or end of a file using Home and End. Press Q to exit the program.

grep [options] searchstring files

The grep command finds a specific search string in the specified files. If the search string is found, the command displays the line in which searchstring was found along with the filename.

-i

Ignores case

-H

Only displays the names of the respective files, but not the text lines

-n

Additionally displays the numbers of the lines in which it found a hit

-l

Only lists the files in which searchstring does not occur

diff [options] file1 file2

The diff command compares the contents of any two files. The output produced by the program lists all lines that do not match. This is frequently used by programmers who need only send their program alterations and not the entire source code.

-q

Only reports whether the two files differ

-u

Produces a unified diff, which makes the output more readable

18.3.1.3. File Systems

mount [options] [device] mountpoint

This command can be used to mount any data media, such as hard disks, CD-ROM drives, and other drives, to a directory of the Linux file system.

-r

Mount read-only

-t filesystem

Specify the file system, commonly ext2 for Linux hard disks, msdos for MS-DOS media, vfat for the Windows file system, and iso9660 for CDs

For hard disks not defined in the file /etc/fstab, the device type must also be specified. In this case, only root can mount it. If the file system should also be mounted by other users, enter the option user in the appropriate line in the /etc/fstab file (separated by commas) and save this change. Further information is available in the mount(1) man page.

umount [options] mountpoint

This command unmounts a mounted drive from the file system. To prevent data loss, run this command before taking a removable data medium from its drive. Normally, only root is allowed to run the commands mount and umount. To enable other users to run these commands, edit the /etc/fstab file to specify the option user for the respective drive.

18.3.2. System Commands

The following section lists a few of the most important commands needed for retrieving system information and controlling processes and the network.

18.3.2.1. System Information

df [options] [directory]

The df (disk free) command, when used without any options, displays information about the total disk space, the disk space currently in use, and the free space on all the mounted drives. If a directory is specified, the information is limited to the drive on which that directory is located.

-h

Shows the number of occupied blocks in gigabytes, megabytes, or kilobytes—in human-readable format

-T

Type of file system (ext2, nfs, etc.)

du [options] [path]

This command, when executed without any parameters, shows the total disk space occupied by files and subdirectories in the current directory.

-a

Displays the size of each individual file

-h

Output in human-readable form

-s

Displays only the calculated total size

free [options]

The command free displays information about RAM and swap space usage, showing the total and the used amount in both categories. See Section 22.1.6, “The free Command” for more information.

-b

Output in bytes

-k

Output in kilobytes

-m

Output in megabytes

date [options]

This simple program displays the current system time. If run as root, it can also be used to change the system time. Details about the program are available in the date(1) man page.

18.3.2.2. Processes

top [options]

top provides a quick overview of the currently running processes. Press H to access a page that briefly explains the main options for customizing the program.

ps [options] [process ID]

If run without any options, this command displays a table of all your own programs or processes—those you started. The options for this command are not preceded by hyphen.

aux

Displays a detailed list of all processes, independent of the owner

kill [options] process ID

Unfortunately, sometimes a program cannot be terminated in the normal way. In most cases, you should still be able to stop such a runaway program by executing the kill command, specifying the respective process ID (see top and ps). kill sends a TERM signal that instructs the program to shut itself down. If this does not help, the following parameter can be used:

-9

Sends a KILL signal instead of a TERM signal, bringing the specified process to an end in almost all cases

killall [options] processname

This command is similar to kill, but uses the process name (instead of the process ID) as an argument, killing all processes with that name.

18.3.2.3. Network

ping [options] hostname or IP address

The ping command is the standard tool for testing the basic functionality of TCP/IP networks. It sends a small data packet to the destination host, requesting an immediate reply. If this works, ping displays a message to that effect, which indicates that the network link is basically functioning.

-c number

Determines the total number of packages to send and ends after they have been dispatched (by default, there is no limitation set)

-f

flood ping: sends as many data packages as possible; a popular means, reserved for root, to test networks

-i value

Specifies the interval between two data packages in seconds (default: one second)

nslookup

The domain name system resolves domain names to IP addresses. With this tool, send queries to name servers (DNS servers).

telnet [options] hostname or IP address [port]

Telnet is actually an Internet protocol that enables you to work on remote hosts across a network. telnet is also the name of a Linux program that uses this protocol to enable operations on remote computers.

[Warning]

Do not use telnet over a network on which third parties can eavesdrop. Particularly on the Internet, use encrypted transfer methods, such as ssh, to avoid the risk of malicious misuse of a password (see the man page for ssh).

18.3.2.4. Miscellaneous

passwd [options] [username]

Users may change their own passwords at any time using this command. The administrator root can use the command to change the password of any user on the system.

su [options] [username]

The su command makes it possible to log in under a different username from a running session. Specify a username and the corresponding password. The password is not required from root, because root is authorized to assume the identity of any user. When using the command without specifying a username, you are prompted for the root password and change to the superuser (root).

-

Use su - to start a login shell for the different user

halt [options]

To avoid loss of data, you should always use this program to shut down your system.

reboot [options]

Does the same as halt except the system performs an immediate reboot.

clear

This command cleans up the visible area of the console. It has no options.

18.3.3. For More Information

There are many more commands than listed in this chapter. For information about other commands or more detailed information, the O'Reilly publication Linux in a Nutshell is recommended.

18.4. The vi Editor

Text editors are still used for many system administration tasks as well as for programming. In the world of Unix, vi stands out as an editor that offers comfortable editing functions and is more ergonomic than many editors with mouse support.

18.4.1. Operating Modes

[Note]Display of Keys

In the following, find several commands that you can enter in vi by just pressing keys. These appear in uppercase as on a keyboard. If you need to enter a key in uppercase, this is stated explicitly by showing a key combination including the Shift key.

Basically, vi makes use of three operating modes: insert mode, command mode, and extended mode. The keys have different functions depending on the mode. On start-up, vi is normally set to the command mode. The first thing to learn is how to switch between the modes:

Command Mode to Insert Mode

There are many possibilities, including A for append, I for insert, or O for a new line under the current line.

Insert Mode to Command Mode

Press Esc to exit the insert mode. vi cannot be terminated in insert mode, so it is important to get used to pressing Esc.

Command Mode to Extended Mode

The extended mode of vi can be activated by entering a colon (:). The extended or ex mode is similar to an independent line-oriented editor that can be used for various simple and more complex tasks.

Extended Mode to Command Mode

After executing a command in extended mode, the editor automatically returns to command mode. If you decide not to execute any command in extended mode, delete the colon with <—. The editor returns to command mode.

It is not possible to switch directly from insert mode to extended mode without first switching to command mode.

vi, like other editors, has its own procedure for terminating the program. You cannot terminate vi while in insert mode. First, exit insert mode by pressing Esc. Subsequently, you have two options:

  1. Exit without saving: To terminate the editor without saving the changes, enter : Q ! in command mode. The exclamation mark (!) causes vi to ignore any changes.

  2. Save and exit: There are several possibilities to save your changes and terminate the editor. In command mode, use Shift+Z Shift+Z. To exit the program saving all changes using the extended mode, enter : W Q. In extended mode, w stands for write and q for quit.

18.4.2. vi in Action

vi can be used as a normal editor. In insert mode, enter text and delete text with the <— and Del keys. Use the arrow keys to move the cursor.

However, these control keys often cause problems, because there are many terminal types that use special key codes. This is where the command mode comes into play. Press Esc to switch from insert mode to command mode. In command mode, move the cursor with H, J, K, and L. The keys have the following functions:

H

Move one character to the left

J

Move one line down

K

Move one line up

L

Move one character to the right

The commands in command mode allow diverse variations. To execute a command several times, simply enter the number of repetitions before entering the actual command. For example, enter 5 L to move the cursor five characters to the right.

A selection of important commands is shown in Table 18.2, “Simple Commands of the vi Editor” This list is far from complete. More complete lists are available in the documentation found in Section 18.4.3, “For More Information”

Table 18.2. Simple Commands of the vi Editor

Esc

Change to command mode

I

Change to insert mode (characters appear at the current cursor position)

A

Change to insert mode (characters are inserted after the current cursor position)

Shift+A

Change to insert mode (characters are added at the end of the line)

Shift+R

Change to replace mode (overwrite the old text)

R

Replace the character under the cursor

O

Change to insert mode (a new line is inserted after the current one)

Shift+O

Change to insert mode (a new line is inserted before the current one)

X

Delete the current character

D D

Delete the current line

D W

Delete up to the end of the current word

C W

Change to insert mode (the rest of the current word is overwritten by the next entries you make)

U

Undo the last command

Ctrl+R

Redo the change that was undone

Shift+J

Join the following line with the current one

.

Repeat the last command


18.4.3. For More Information

vi supports a wide range of commands. It enables the use of macros, shortcuts, named buffers, and many other useful features. A detailed description of the various options would exceed the scope of this manual. SUSE Linux Enterprise comes with vim (vi improved), an improved version of vi. There are numerous information sources for this application:

[Important]The VIM License

vim is charityware, which means that the authors do not charge any money for the software but encourage you to support a nonprofit project with a monetary contribution. This project solicits help for poor children in Uganda. More information is available online at http://iccf-holland.org/index.html, http://www.vim.org/iccf/, and http://www.iccf.nl/.