Shell and bash scripts

Copyright © 2006– 2021 SUSE LLC and contributors. All rights reserved.

Copyright © 2021– 2021 Didier Spaier for the Slint distribution. All rights reserved.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or (at your option) version 1.3; with the Invariant Section being this copyright notice and license. A copy of the license version 1.2 is included in the section entitled GNU Free Documentation License.

This document is an adaptation for Slint of the part IV The Bash Shell of openSUSE Leap 15.3 StartUp


Table of Contents

1. Shell basics
Starting a shell
Entering commands
Using commands without options
Using commands with options
Bash shortcut keys
Getting help
Working with files and directories
Examples for working with files and directories
Becoming root
Using su
Using sudo
File access permissions
Permissions for user, group and others
Files and folders
Modifying file permissions
Time-saving features of Bash
Examples for using history, completion and wildcards
Editing texts
Example: editing with vi
Searching for files or contents
Examples for searching
Viewing text files
Redirection and pipes
Examples for redirection and pipe
Starting programs and handling processes
Archives and data compression
Important Linux commands
File commands
System commands
More information
2. Bash and Bash scripts
What is the shell?
Bash configuration files
The directory structure
Writing shell scripts
Redirecting command events
Using aliases
Using variables in Bash
Using argument variables
Using variable substitution
Grouping and combining commands
Working with common flow constructs
The if control command
Creating loops with the for command
More information
A. GNU free documentation license

List of Tables

1.1. Access permissions for files and directories
2.1. Bash configuration files for login shells
2.2. Bash configuration files for non-login shells
2.3. Special files for Bash
2.4. Overview of a standard directory tree
2.5. Useful environment variables

List of Examples

1.1. Access permissions for files and folders
1.2. Access permissions for files and folders
2.1. A shell script printing a text

Chapter 1. Shell basics

When working with Linux, you can communicate with the system almost without ever requiring a command line interpreter (the shell). After 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 operating system. The graphical user interface in Linux is initially configured during installation and used by desktop environments such as Mate of XFCE.

Nevertheless, it is useful to have some basic knowledge of working with a shell because you might encounter situations where the graphical user interface is not available. For example, if some problem with the X Window System occurs. If you are not familiar with a shell, you might feel a bit uncomfortable at first when entering commands, but the more you get used to it, the more you will realize that the command line is often the quickest and easiest way to perform some daily tasks.

For Unix or Linux, several shells are available which differ slightly in behavior and in the commands they accept. The default shell in Slint is Bash (GNU Bourne-Again Shell).

The following sections will guide you through your first steps with the Bash shell and will show you how to complete some basic tasks via the command line. If you are interested in learning more or rather feel like a shell power user already, refer to Chapter 2, Bash and Bash scripts.

Starting a shell

Basically, there are two different ways to start a shell from the graphical user interface which usually shows after you have booted your computer:

  • you can leave the graphical user interface or

  • you can start a terminal window within the graphical user interface.

While the first option is always available, you can only make use of the second option when you are already logged in to a desktop such as KDE or GNOME. Whichever way you choose, there is always a way back and you can switch back and forth between the shell and the graphical user interface.

If you want to give it a try, press Ctrl+Alt+F2 to leave the graphical user interface. The graphical user interface disappears and you are taken to a shell which prompts you to log in. Type your username and press Enter. Then type your password and press Enter. The prompt now changes and shows some useful information as in the following example:

 1   2   3
tux@darkstar:~$ 

1

Your login.

2

The hostname of your computer.

3

Path to the current directory. Directly after login, the current directory usually is your home directory, indicated by the ~ symbol (tilde) .

When you are logged in at a remote computer the information provided by the prompt always shows you which system you are currently working on.

When the cursor is located behind this prompt, you can pass commands directly to your computer system. For example, you can now enter ls -l to list the contents of the current directory in a detailed format. If this is enough for your first encounter with the shell and you want to go back to the graphical user interface, you should log out from your shell session first. To do so, type exit and press Enter. Then press Alt+F7 to switch back to the graphical user interface. You will find your desktop and the applications running on it unchanged.

When you are already logged in to the GNOME or the KDE desktop and want to start a terminal window within the desktop, press Alt+F2 and enter konsole (for KDE) or gnome-terminal (for GNOME). This opens a terminal window on your desktop. As you are already logged in to your desktop, the prompt shows information about your system as described above. You can now enter commands and execute tasks just like in any shell which runs parallel to your desktop. To switch to another application on the desktop just click on the corresponding application window or select it from the taskbar of your panel. To close the terminal window press Alt+F4.

Entering commands

As soon as the prompt appears on the shell it is ready to receive and execute commands. A command can consist of several elements. The first element is the actual command, followed by parameters or options. You can type a command and edit it by using the following keys: , , Home, End, <—, Del, and Space. You can correct typing errors or add options. The command is not executed until you press Enter.

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 —or if you explicitly ask for them by executing a command with a certain option.

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

Using commands without options

In the section called “Permissions for user, group and others” you already got to know one of the most basic commands: ls, which used to list the contents of a directory. This command can be used with or without options. Entering the plain ls command shows the contents of the current directory:

tux@darkstar:~$ ls
bin Desktop Documents public_html tux.txt
tux@darkstar:~$ 

Files in Linux may have a file extension or a suffix, 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 in the Bash shell give you a hint: directories are usually shown in blue, files in black.

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 carry out specific tasks. Options are separated from the command with a blank and are usually prefixed with a hyphen. The ls -l command shows the contents of the same directory in full detail (long listing format):

tux@darkstar:~$ ls -l
drwxr-xr-x 1 tux users     48 2015-06-23 16:08 bin
drwx---r-- 1 tux users  53279 2015-06-21 13:16 Desktop
drwx------ 1 tux users    280 2015-06-23 16:08 Documents
drwxr-xr-x 1 tux users  70733 2015-06-21 09:35 public_html
-rw-r--r-- 1 tux users  47896 2015-06-21 09:46 tux.txt
tux@darkstar:~$ 

This output shows the following information about each object:

drwxr-xr-x1 12 tux3 users4 485 2006-06-23 16:086 bin7 

1

Type of object and access permissions. For further information, refer to the section called “Permissions for user, group and others”.

2

Number of hard links to this file.

3

Owner of the file or directory. For further information, refer to the section called “Permissions for user, group and others”.

4

Group assigned to the file or directory. For further information, refer to the section called “Permissions for user, group and others”.

5

File size in bytes.

6

Date and time of the last change.

7

Name of the object.

Usually, you can combine several options by prefixing only the first option with a hyphen and then write the others consecutively without a blank. For example, if you want to see all files in a directory in long listing format, you can combine the two options -l and -a (show all files) for the ls command. Executing ls -la shows also hidden files in the directory, indicated by a dot in front (for example, .hiddenfile).

The list of contents you get with ls is sorted alphabetically by filenames. But like in a graphical file manager, you can also sort the output of ls -l according to various criteria such as date, file extension or file size:

  • For date and time, use ls -lt (displays newest first).

  • For extensions, use ls -lx (displays files with no extension first).

  • For file size, use ls -lS (displays largest first).

To revert the order of sorting, add -r as an option to your ls command. For example, ls -lr gives you the contents list sorted in reverse alphabetical order, ls -ltr shows the oldest files first. There are lots of other useful options for ls. In the following section you will learn how to investigate them.

Bash shortcut keys

After having entered several commands, your shell will begin to fill up with all sorts of commands and the corresponding outputs. In the following table, find some useful shortcut keys for navigating and editing in the shell.

Shortcut Key

Function

Ctrl+L

Clears the screen and moves the current line to the top of the page.

Ctrl+C

Aborts the command which is currently being executed.

Shift+Page ↑

Scrolls upwards.

Shift+Page ↓

Scrolls downwards.

Ctrl+U

Deletes from cursor position to start of line.

Ctrl+K

Deletes from cursor position to the end of line.

Ctrl+D

Closes the shell session.

,

Browses in the history of executed commands.

Getting help

If you remember the name of command but are not sure about the options or the syntax of the command, choose one of the following possibilities:

--help/-h option

If you only want to look up the options of a certain command, try entering the command followed by a space and --help. This --help option exists for many commands. For example, ls --help displays all the options for the ls command.

Manual pages

To learn more about the various commands, you can also use the manual pages. Manual pages also give a short description of what the command does. They can be accessed with man followed by the name of the command, for example, man ls.

Man pages are displayed directly in the shell. To navigate them, use the following keys:

  • Move up and down with Page ↑ and Page ↓

  • Move between the beginning and the end of a document with Home and End

  • Quit the man page viewer by pressing Q

For more information about the man command, use man man.

Info pages

Info pages usually provide even more information about commands. To view the info page for a certain command, enter info followed by the name of the command (for example, info ls).

Info pages are displayed directly in the shell. To navigate them, use the following keys:

  • Use Space to move forward a section (node). Use <— to move backward a section.

  • Move up and down with Page ↑ and Page ↓

  • Quit the info page viewer by pressing Q

Note that man pages and info pages do not exist for all commands. Sometimes both are available (usually for key commands), sometimes only a man page or an info page exists, and sometimes neither of them are available.

Working with files and directories

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:

Absolute path

The entire path from the root directory (/) to the relevant file or directory. For example, the absolute path to a text file named file.txt in your Documents directory might be:

/home/tux/Documents/file.txt
Relative path

The path from the current working directory to the relevant file or directory. If your current working directory is /home/tux, the relative path file.txt in your Documents directory is:

Documents/file.txt

However, if your working directory is /home/tux/Music instead, you need to move up a level to /home/tux (with ..) before you can go further down:

../Documents/file.txt

Paths contain file names, directories or both, separated by slashes. Absolute paths always start with a slash. Relative paths do not have a slash at the beginning, but can have one or two dots.

When entering commands, you can choose either way to specify a path, depending on your preferences or the amount of typing, both will lead to the same result. To change directories, use the cd command and specify the path to the directory.

Handling blanks in filenames or directory names

If a filename or the name of a directory contains a space, either escape the space using a back slash (\) in front of the blank or enclose the filename in single quotes. Otherwise Bash interprets a filename like My Documents as the names of two files or directories, My and Documents in this case.

When specifying paths, the following shortcuts can save you a lot of typing:

  • The tilde symbol (~) is a shortcut for home directories. For example, to list the contents of your home directory, use ls ~. To list the contents of another user's home directory, enter ls ~USERNAME (or course, this will only work if you have permission to view the contents, see the section called “File access permissions”). For example, entering ls ~tux would list the contents of the home directory of a user named tux. You can use the tilde symbol as shortcut for home directories also if you are working in a network environment where your home directory may not be called /home but can be mapped to any directory in the file system.

    From anywhere in the file system, you can reach your home directory by entering cd ~ or by simply entering cd without any options.

  • When using relative paths, refer to the current directory with a dot (.). This is mainly useful for commands such as cp or mv by which you can copy or move files and directories.

  • The next higher level in the tree is represented by two dots (..). In order to switch to the parent directory of your current directory, enter cd .., to go up two levels from the current directory enter cd ../.. etc.

To apply your knowledge, find some examples below. They address basic tasks you may want to execute with files or folders using Bash.

Examples for working with files and directories

Suppose you want to copy a file located somewhere in your home directory to a subdirectory of /tmp that you need to create first.

Procedure 1.1. Creating and changing directories

From your home directory create a subdirectory in /tmp:

  1. Enter

    tux@darkstar:~$ mkdir /tmp/test

    mkdir stands for make directory. This command creates a new directory named test in the /tmp directory. In this case, you are using an absolute path to create the test directory.

  2. To check what happened, now enter

    tux@darkstar:~$ ls -l /tmp

    The new directory test should appear in the list of contents of the /tmp directory.

  3. Switch to the newly created directory with

    tux@darkstar:~$ cd /tmp/test

Procedure 1.2. Creating and copying files

Now create a new file in a subdirectory of your home directory and copy it to /tmp/test. Use a relative path for this task.

Overwriting of existing files

Before copying, moving or renaming a file, check if your target directory already contains a file with the same name. If yes, consider changing one of the filenames or use cp or mv with options like -i, which will prompt before overwriting an existing file. Otherwise Bash will overwrite the existing file without confirmation.

  1. To list the contents of your home directory, enter

    tux@darkstar:~$ ls -l ~

    It should contain a subdirectory called Documents by default. If not, create this subdirectory with the mkdir command you already know:

    tux@darkstar:~$ mkdir ~/Documents
  2. To create a new, empty file named myfile.txt in the Documents directory, enter

    tux@darkstar:~$ touch ~/Documents/myfile.txt

    Usually, the touch command updates the modification and access date for an existing file. If you use touch with a filename which does not exist in your target directory, it creates a new file.

  3. Enter

    tux@darkstar:~$ ls -l ~/Documents

    The new file should appear in the list of contents.

  4. To copy the newly created file, enter

    tux@darkstar:~$ cp ~/Documents/myfile.txt .

    Do not forget the dot at the end.

    This command tells Bash to go to your home directory and to copy myfile.txt from the Documents subdirectory to the current directory, /tmp/test, without changing the name of the file.

  5. Check the result by entering

    tux@darkstar:~$ ls -l

    The file myfile.txt should appear in the list of contents for /tmp/test.

Procedure 1.3. Renaming and removing files or directories

Now suppose you want to rename myfile.txt into tuxfile.txt. Finally you decide to remove the renamed file and the test subdirectory.

  1. To rename the file, enter

    tux@darkstar:~$ mv myfile.txt tuxfile.txt
  2. To check what happened, enter

    tux@darkstar:~$ ls -l

    Instead of myfile.txt, tuxfile.txt should appear in the list of contents.

    mv stands for move and is used with two options: the first option specifies the source, the second option specifies the target of the operation. You can use mv either

    • to rename a file or a directory,

    • to move a file or directory to a new location or

    • to do both in one step.

  3. Coming to the conclusion that you do not need the file any longer, you can delete it by entering

    tux@darkstar:~$ rm tuxfile.txt 

    Bash deletes the file without any confirmation.

  4. Move up one level with cd .. and check with

    tux@darkstar:~$ ls -l test

    if the test directory is empty now.

  5. If yes, you can remove the test directory by entering

    tux@darkstar:~$ rmdir test

Becoming root

root, also called the superuser, has privileges which authorize them to access all parts of the system and to execute administrative tasks. They have the unrestricted capacity to make changes to the system and they have unlimited access to all files. Therefore, performing some administrative tasks or running certain programs such as slapt-get requires root permissions.

Using su

In order to temporarily become root in a shell, proceed as follows:

  1. Enter su -. You are prompted for the root password.

  2. Enter the password. If you mistyped the root password, the shell displays a message. In this case, you have to re-enter su before retyping the password. If your password is correct, a hash symbol # appears at the end of the prompt, signaling that you are acting as root now.

  3. You are now in that home directory of the root user, which is /root/ as shows the new prompt and the command pwd (for Print Working Directory) that you can type after the prompt to check:

    root@darkstar:~# pwd
    /root
    root@darkstar:~#
    
  4. After having completed your tasks as root, switch back to your normal user account. To do so, enter

    tux@darkstar:~$ exit
    or just press Ctrl+D

    The hash symbol disappears and you are acting as normal user again. You are back to the last directory where you were before becoming root, as you can check:

    tux@darkstar:~$ pwd
    /home/tux
    tux@darkstar:~$ 
    

Using sudo

Alternatively, you can also use sudo (superuser do) to execute some tasks which normally are for root only. With sudo, administrators can grant certain users root privileges for some commands. Depending on the system configuration, users can then run root commands by entering their normal password only. Due to a timestamp function, users are only granted a ticket for a restricted period of time after having entered their password. The ticket usually expires after a few minutes.

tux@darkstar:~$ sudo  command

After you have entered the password which you are prompted for, the command is executed. If you enter a second root command shortly after that, you are not prompted for the password again, because your ticket is still valid. After a certain amount of time, the ticket automatically expires and the password is required again. This also prevents unauthorized persons from gaining root privileges in case a user forgets to switch back to their normal user account again and leaves a root shell open.

sudo is not enabled by default in Slint, but can be configured after installation.

File access permissions

In Linux, objects such as files or folders or processes generally belong to the user who created or initiated them. There are some exceptions to this rule. For more information about the exceptions, refer to ???. The group which is associated with a file or a folder depends on the primary group the user belongs to when creating the object.

taroth 060522: what does determine the access permissions which are set when creating a new file? -toms: umask - taroth 061014: no time left, explain or refer to in next revision When you create a new file or directory, initial access permissions for this object are set according to a predefined scheme. As an owner of a file or directory, you can change the access permissions for this object. For example, you can protect files holding sensitive data against read access by other users and you can authorize the members of your group or other users to write, read, or execute several of your files where appropriate. As root, you can also change the ownership of files or folders.

Permissions for user, group and others

Three permission sets are defined for each file object on a Linux system. These sets include the read, write, and execute permissions for each of three types of users—the owner, the group, and other users.

The following example shows the output of an ls -l command in a shell. This command lists the contents of a directory and shows the details for each file and folder in that directory.

Example 1.1. Access permissions for files and folders

-rw-r----- 1 tux users      0 2015-06-23 16:08 checklist.txt
-rw-r--r-- 1 tux users  53279 2015-06-21 13:16 gnome_quick.xml
-rw-rw---- 1 tux users      0 2015-06-23 16:08 index.htm
-rw-r--r-- 1 tux users  70733 2015-06-21 09:35 kde-start.xml
-rw-r--r-- 1 tux users  47896 2015-06-21 09:46 kde_quick.xml
drwxr-xr-x 2 tux users     48 2015-06-23 16:09 local
-rwxr--r-- 1 tux users 624398 2015-06-23 15:43 tux.sh

As shown in the third column, all objects belong to user tux. They are assigned to the group users which is the primary group the user tux belongs to. To retrieve the access permissions the first column of the list must be examined more closely. Let's have a look at the file kde-start.xml:

Type

User Permissions

Group Permissions

Permissions for Others

-

rw-

r--

r--

The first column of the list consists of one leading character followed by nine characters grouped in three blocks. The leading character indicates the file type of the object: in this case, the hyphen () shows that kde-start.xml is a file. If you find the character d instead, this shows that the object is a directory, like local in Example 1.1, “Access permissions for files and folders”.

The next three blocks show the access permissions for the owner, the group and other users (from left to right). Each block follows the same pattern: the first position shows read permissions (r), the next position shows write permissions (w), the last one shows execute permission (x). A lack of either permission is indicated by -. In our example, the owner of kde-start.xml has read and write access to the file but cannot execute it. The users group can read the file but cannot write or execute it. The same holds true for the other users as shown in the third block of characters.

Files and folders

Access permissions have a slightly different impact depending on the type of object they apply to: file or directory. The following table shows the details:

Table 1.1. Access permissions for files and directories

Access Permission

File

Folder

Read (r)

Users can open and read the file.

Users can view the contents of the directory. Without this permission, users cannot list the contents of this directory with ls -l, for example. However, if they only have execute permission for the directory, they can nevertheless access certain files in this directory if they know of their existence.

Write (w)

Users can change the file: They can add or drop data and can even delete the contents of the file. However, this does not include the permission to remove the file completely from the directory as long as they do not have write permissions for the directory where the file is located.

Users can create, rename or delete files in the directory.

Execute (x)

Users can execute the file. This permission is only relevant for files like programs or shell scripts, not for text files. If the operating system can execute the file directly, users do not need read permission to execute the file. However, if the file must me interpreted like a shell script or a perl program, additional read permission is needed.

Users can change into the directory and execute files there. If they do not have read access to that directory they cannot list the files but can access them nevertheless if they know of their existence.


Note that access to a certain file is always dependent on the correct combination of access permissions for the file itself and the directory it is located in.

Modifying file permissions

In Linux, objects such as files or folder or processes generally belong to the user who created or initiated them. The group which is associated with a file or a folder depends on the primary group the user belongs to when creating the object. When you create a new file or directory, initial access permissions for this object are set according to a predefined scheme. For further details refer to the section called “File access permissions”.

As the owner of a file or directory (and, of course, as root), you can change the access permissions to this object.

To change object attributes like access permissions of a file or folder, use the chmod command followed by the following parameters:

  • the users for which to change the permissions,

  • the type of access permission you want to remove, set or add and

  • the files or folders for which you want to change permissions separated by spaces.

The users for which you can change file access permissions fall into the following categories: the owner of the file (user, u), the group that own the file (group, g) and the other users (others, o). You can add, remove or set one or more of the following permissions: read, write or execute.

As root, you can also change the ownership of a file: with the command chown (change owner) you can transfer ownership to a new user.

Examples for changing access permissions and ownership

The following example shows the output of an ls -l command in a shell.

Example 1.2. Access permissions for files and folders

-rw-r----- 1 tux users      0 2015-06-23 16:08 checklist.txt
-rw-r--r-- 1 tux users  53279 2015-06-21 13:16 gnome_quick.xml
-rw-rw---- 1 tux users      0 2015-06-23 16:08 index.htm
-rw-r--r-- 1 tux users  70733 2015-06-21 09:35 kde-start.xml
-rw-r--r-- 1 tux users  47896 2015-06-21 09:46 kde_quick.xml
drwxr-xr-x 2 tux users     48 2015-06-23 16:09 local
-r-xr-xr-x 1 tux users 624398 2015-06-23 15:43 tux.jpg

In the example above, user tux owns the file kde-start.xml and has read and write access to the file but cannot execute it. The users group can read the file but cannot write or execute it. The same holds true for the other users as shown by the third block of characters.

Procedure 1.4. Changing access permissions

Suppose you are tux and want to modify the access permissions to your files:

  1. If you want to grant the users group also write access to kde-start.xml, enter

    tux > chmod g+w kde-start.xml
  2. To grant the users group and other users write access to kde-start.xml, enter

    tux > chmod go+w kde-start.xml
  3. To remove write access for all users, enter

    tux > chmod -w kde-start.xml

    If you do not specify any kind of users, the changes apply to all users— the owner of the file, the owning group and the others. Now even the owner tux does not have write access to the file without first reestablishing write permissions.

  4. To prohibit the users group and others to change into the directory local, enter

    tux > chmod go-x local
  5. To grant others write permissions for two files, for kde_quick.xml and gnome_quick.xml, enter

    tux > chmod o+w  kde_quick.xml gnome_quick.xml

Procedure 1.5. Changing ownership

Suppose you are tux and want to transfer the ownership of the file kde_quick.xml to an other user, named wilber. In this case, proceed as follows:

  1. Enter the username and password for root.

  2. Enter

    root # chown wilber kde_quick.xml
  3. Check what happened with

    tux > ls -l kde_quick.xml

    You should get the following output:

    -rw-r--r-- 1 wilber users  47896 2006-06-21 09:46 kde_quick.xml
  4. If the ownership is set according to your wishes, switch back to your normal user account.

Time-saving features of Bash

Entering commands in Bash can involve a lot of typing. This section introduces some features that can save you both time and typing.

History

By default, Bash remembers commands you have entered. This feature is called history. You can browse through commands that have been entered before, select one you want to repeat and then execute it again. To do so, press repeatedly until the desired command appears at the prompt. To move forward through the list of previously entered commands, press . For easier repetition of a certain command from Bash history, just type the first letter of the command you want to repeat and press Page ↑.

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

You can also search for a certain command in the history. Press Ctrl+R to start an incremental search function. showing the following prompt:

tux@darkstar:~$ (reverse-i-search)`': 

Just type one or several letters from the command you are searching for. Each character you enter narrows down the search. The corresponding search result is shown on the right side of the colon whereas your input appears on the left of the colon. To accept a search result, press Esc. The prompt now changes to its normal appearance and shows the command you chose. You can now edit the command or directly execute it by pressing Enter.

Completion

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 →| (Tabulator). 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 it becomes ambiguous again. 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 →|, 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).

Wild cards

You can replace one or more characters in a filename with a wild card for pathname expansion. Wild cards are characters that can stand for other characters. There are three different types of these in Bash:

Wild Card

Function

?

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.

Examples for using history, completion and wildcards

The following examples illustrate how to make use of these convenient features of Bash.

Procedure 1.6. Using history and completion

If you already did the example the section called “Examples for working with files and directories”, your shell buffer should be filled with commands which you can retrieve using the history function.

  1. Press repeatedly until cd ~ appears.

  2. Press Enter to execute the command and to switch to your home directory.

    By default, your home directory contains two subdirectories starting with the same letter, Documents and Desktop.

  3. Type cd D and press →|.

    Nothing happens since Bash cannot identify to which one of the subdirectories you want to change.

  4. Press →| again to see the list of possible choices:

    tux@darkstar:~$ cd D
    Desktop/ Documents/ Downloads/
    tux@darkstar:~$ cd D
  5. The prompt still shows your initial input. Type the next character of the subdirectory you want to go to and press →| again.

    Bash now completes the path.

  6. You can now execute the command with Enter.

Procedure 1.7. Using wildcards

Now suppose that your home directory contains several files with various file extensions. It also holds several versions of one file which you saved under different filenames myfile1.txt, myfile2.txt etc. You want to search for certain files according to their properties.

  1. First, create some test files in your home directory:

    1. Use the touch command to create several (empty) files with different file extensions, for example .pdf, .xml and .jpg.

      You can do this consecutively (do not forget to use the Bash history function) or with only one touch command: simply add several filenames separated by a space.

    2. Create at least two files that have the same file extension, for example .html.

    3. To create several versions of one file, enter

      tux@darkstar:~$ touch myfile{1..5}.txt

      This command creates five consecutively numbered files: myfile1.txt, …, myfile5.txt.

    4. List the contents of the directory. It should look similar to this:

      tux@darkstar:~$ ls -l
      -rw-r--r-- 1 tux users   0 2006-07-14 13:34 foo.xml
      -rw-r--r-- 1 tux users   0 2006-07-14 13:47 home.html
      -rw-r--r-- 1 tux users   0 2006-07-14 13:47 index.html
      -rw-r--r-- 1 tux users   0 2006-07-14 13:47 toc.html
      -rw-r--r-- 1 tux users   0 2006-07-14 13:34 manual.pdf
      -rw-r--r-- 1 tux users   0 2006-07-14 13:49 myfile1.txt
      -rw-r--r-- 1 tux users   0 2006-07-14 13:49 myfile2.txt
      -rw-r--r-- 1 tux users   0 2006-07-14 13:49 myfile3.txt
      -rw-r--r-- 1 tux users   0 2006-07-14 13:49 myfile4.txt
      -rw-r--r-- 1 tux users   0 2006-07-14 13:49 myfile5.txt
      -rw-r--r-- 1 tux users   0 2006-07-14 13:32 tux.png
  2. With wild cards, select certain subsets of the files according to various criteria:

    1. To list all files with the .html extension, enter

      tux@darkstar:~$ ls -l *.html
    2. To list all versions of myfile.txt, enter

      tux@darkstar:~$ ls -l myfile?.txt

      Note that you can only use the ? wild card here because the numbering of the files is single-digit. As soon as you have a file named myfile10.txt you must to use the * wild card to view all versions of myfile.txt (or add another question mark, so your string looks like myfile??.txt).

    3. To remove, for example, version 1-3 and version 5 of myfile.txt, enter

      tux@darkstar:~$ rm myfile[1-3,5].txt
    4. Check the result with

      tux@darkstar:~$ ls -l

      Of all myfile.txt versions only myfile4.txt should be left.

You can also combine several wild cards in one command. In the example above, rm myfile[1-3,5].* would lead to the same result as rm myfile[1-3,5].txt because there are only files with the extension .txt available.

Using wildcards in rm commands

Wildcards in a rm command can be very useful but also dangerous: you might delete more files from your directory than intended. To see which files would be affected by the rm, run your wildcard string with ls instead of rm first.

Editing texts

In order to edit files from the command line, you will need to know the vi editor. vi is a default editor which can be found on nearly every UNIX/Linux system. It can run several operating modes in which the keys you press have different functions. This does not make it very easy for beginners, but you should know at least the most basic operations with vi. There may be situations where no other editor than vi is available.

Basically, vi makes use of three operating modes:

command mode

In this mode, vi accepts certain key combinations as commands. Simple tasks such as searching words or deleting a line can be executed.

insert mode

In this mode, you can write normal text.

extended mode

In this mode, also known as colon mode (as you have to enter a colon to switch to this mode), vi can execute also more complex tasks such as searching and replacing text.

In the following (very simple) example, you will learn how to open and edit a file with vi, how to save your changes and quit vi.

Example: editing with vi

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.

  1. To create and open a new file with vi, enter

    tux@darkstar:~$ vi textfile.txt

    By default, vi opens in command mode in which you cannot enter text.

  2. Press I to switch to insert mode. The bottom line changes and indicates that you now can insert text.

  3. Write some sentences. If you want to insert a new line, first press Esc to switch back to command mode. Press O to insert a new line and to switch to insert mode again.

  4. In the insert mode, you can edit the text with the arrow keys and with Del.

  5. To leave vi, press Esc to switch to command mode again. Then press : which takes you to the extended mode. The bottom line now shows a colon.

  6. To leave vi and save your changes, type wq (w for write; q for quit) and press Enter. If you want to save the file under a different name, type w FILENAME and press Enter.

    To leave vi without saving, type q! instead and press Enter.

Searching for files or contents

Bash offers you several commands to search for files and to search for the contents of files:

find

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.

grep

The grep command finds a specific search string in the specified text files. If the search string is found, the command displays the line in which searchstring was found, along with the filename. If desired, use wild cards to specify filenames.

Examples for searching

  • To search your home directory for all occurrences of filenames that contain the file extension .txt, use:

    tux@darkstar:~$ find ~ -name '*.txt' -print
  • To search a directory (in this case, your home directory) for all occurrences of files which contain, for example, the word music, use:

    tux@darkstar:~$ grep music ~/*

    grep is case-sensitive by default. Hence, with the command above you will not find any files containing Music.To ignore case, use the -i option.

  • To use a search string which consists of more than one word, enclose the string in double quotation marks, for example:

    tux@darkstar:~$ grep "music is great" ~/*

Viewing text files

When searching for the contents of a file with grep, the output gives you the line in which the searchstring was found along with the filename. Often this contextual information is still not enough information to decide whether you want to open and edit this file. Bash offers you several commands to have a quick look at the contents of a text file directly in the shell, without opening an editor.

head

With head you can view the first lines of a text file. If you do not specify the command any further, head shows the first 10 lines of a text file.

tail

The tail command is the counterpart of head. If you use tail without any further options it displays the last 10 lines of a text file. This can be very useful to view log files of your system, where the most recent messages or log entries are usually found at the end of the file.

less

With less, display the whole contents of a text file. To move up and down half a page use Page ↑ and Page ↓. Use Space to scroll down one page. Home takes you to the beginning, and End to the end of the document. To end the viewing mode, press Q.

most

Instead of less, you can also use the program most. It has basically the same function—however, it is has more features,

cat

The cat command displays the contents of a file, printing the entire contents to the screen without interruption. As cat does not allow you to scroll it is not very useful as viewer but it is rather often used in combination with other commands.

Redirection and pipes

Sometimes it would be useful if you could write the output of a command to a file for further editing or if you could combine several commands, using the output of one command as the input for the next one. The shell offers this function by means of redirection or pipes.

Normally, the standard output in the shell is your screen (or an open shell window) and the standard input is the keyboard. With certain symbols you can redirect the input or the output to another object, such as a file or another command.

Redirection

With > you can forward the output of a command to a file (output redirection), with < you can use a file as input for a command (input redirection).

Pipe

By means of a pipe symbol | you can also redirect the output: with a pipe, you can combine several commands, using the output of one command as input for the next command. In contrast to the other redirection symbols > and <, the use of the pipe is not constrained to files.

Examples for redirection and pipe

  1. To write the output of a command like ls to a file, enter

    tux@darkstar:~$ ls -l > filelist.txt

    This creates a file named filelist.txt that contains the list of contents of your current directory as generated by the ls command.

    However, if a file named filelist.txt already exists, this command overwrites the existing file. To prevent this, use >> instead of >. Entering

    tux@darkstar:~$ ls -l >> filelist.txt 

    simply appends the output of the ls command to an already existing file named filelist.txt. If the file does not exist, it is created.

  2. Redirections also works the other way round. Instead of using the standard input from the keyboard for a command, you can use a file as input:

    tux@darkstar:~$ sort < filelist.txt

    This will force the sort command to get its input from the contents of filelist.txt. The result is shown on the screen. Of course, you can also write the result into another file, using a combination of redirections:

    tux@darkstar:~$ sort < filelist.txt > sorted_filelist.txt
  3. If a command generates a lengthy output, like ls -l may do, it may be useful to pipe the output to a viewer like less to be able to scroll through the pages. To do so, enter

    tux@darkstar:~$ ls -l | less

    The list of contents of the current directory is shown in less.

    The pipe is also often used in combination with the grep command in order to search for a certain string in the output of another command. For example, if you want to view a list of files in a directory which are owned by the user tux, enter

    tux@darkstar:~$ ls -l | grep tux

Starting programs and handling processes

As you have seen in the section called “Editing texts”, programs can be started from the shell. Applications with a graphical user interface need the X Window System and can only be started from a terminal window within a graphical user interface. For example, if you want to open a file named vacation.pdf in your home directory from a terminal window in Mate of XFCE, simply run atril ~/vacation.pdf (or evince ~/vacation.pdf) to start a PDF viewer displaying your file.

When looking at the terminal window again you will realize that the command line is blocked as long as the PDF viewer is open, meaning that your prompt is not available. To change this, press Ctrl+Z to suspend the process and enter bg to send the process to the background.

Now you can still have a look at vacation.pdf while your prompt is available for further commands. An easier way to achieve this is by sending a process to the background directly when starting it. To do so, add an ampersand at the end of the command:

tux@darkstar:~$ okular ~/vacation.pdf &

If you have started several background processes (also named jobs) from the same shell, the jobs command gives you an overview of the jobs. It also shows the job number in brackets and their status:

tux@darkstar:~$ jobs
[1]   Running        okular book.opensuse.startup-xep.pdf &
[2]-  Running        okular book.opensuse.reference-xep.pdf &
[3]+  Stopped        man jobs

To bring a job to the foreground again, enter fg JOB_NUMBER.

Whereas job only shows the background processes started from a specific shell, the ps command (run without options) shows a list of all your processes—those you started. Find an example output below:

tux@darkstar:~$ ps
PID TTY          TIME CMD
15500 pts/1    00:00:00 bash
28214 pts/1    00:00:00 okular
30187 pts/1    00:00:00 kwrite
30280 pts/1    00:00:00 ps

In case a program cannot be terminated in the normal way, use the kill command to stop the process (or processes) belonging to that program. To do so, specify the process ID (PID) shown by the output of ps. For example, to shut down the KWrite editor in the example above, enter

tux@darkstar:~$ kill 30187

This sends a TERM signal that instructs the program to shut itself down.

Alternatively, if the program or process you want to terminate is a background job and is shown by the jobs command, you can also use the kill command in combination with the job number to terminate this process. When identifying the job with the job number, you must prefix the number with a percent character (%):

tux@darkstar:~$ kill %JOB_NUMBER

If kill does not help—as is sometimes the case for runaway programs—try

tux@darkstar:~$ kill -9 PID

This sends a KILL signal instead of a TERM signal, usually bringing the specified process to an end.

This section is intended to introduce the most basic set of commands for handling jobs and processes. Find an overview for system administrators in ???.

Archives and data compression

On Linux, there are two types of commands that make data easier to transfer:

  • Archivers, which create a big file out of several smaller ones. The most commonly used archiver is tar, another example is cpio.

  • Compressors, which losslessly make a file smaller. The most commonly used compressors are gzip and bzip2.

When combining these two types of commands, their effect is comparable to the compressed archive files that are prevalent on other operating systems, for example, ZIP or RAR.

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

Procedure 1.8. Archiving files

  1. Open a shell.

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

  3. Commpress the file with:

    tux@darkstar:~$ 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.

    The test directory with all its files and directories has remained unchanged on your hard disk.

  4. View the contents of the archive file with:

    tux@darkstar:~$ tar -tf testarchive.tar
  5. To unpack the archive, use:

    tux@darkstar:~$ tar -xvf testarchive.tar

    If files in your current directory are named the same as the files in the archive, they will be overwritten without warning.

To compress files, use gzip or, for better compression, bzip2.

Procedure 1.9. Compressing a file

  1. For this example, reuse the archive testarchive.tar from Procedure 1.8, “Archiving files”.

    To compress the archive, use:

    tux@darkstar:~$ gzip testarchive.tar

    With ls, now see that the file testarchive.tar is no longer there and that the file testarchive.tar.gz has been created instead.

    As an alternative, use bzip2 testarchive.tar which works analogously but provides somewhat better compression.

  2. Now decompress and unarchive the file again:

    • This can be done in two steps by first decompressing and then unarchiving the file:

      tux@darkstar:~$ gzip --decompress testarchive.tar.gz
      tux@darkstar:~$ tar -xvf testarchive.tar
      
    • You can also decompress and unarchive in one step:

      tux@darkstar:~$ tar -xvf testarchive.tar

    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.

Important Linux commands

This section provides an overview of the most important Linux 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.

Adjust the parameters 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.

File commands

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

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 USER_NAME[:GROUP] FILES

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

-R

Changes files and directories in all subdirectories

chgrp OPTIONS GROUP_NAME FILES

Transfers the group ownership of a given file to the group with the specified group name. The file owner can change group ownership only 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 several 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.

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.

Commands to access file contents

file OPTIONS FILES

In Linux, files can have a file extensions but do not need to have one. The file determines the file type of a given file. With the output of file, you can then choose an appropriate application with which to open the file.

-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 Page ↑ and Page ↓ or a full screen page down with Space. Jump to the beginning or end of a file using Home and End. Press Q to quit the program.

grep OPTIONS SEARCH_STRING 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 SEARCH_STRING was found along with the file name.

-i

Ignores case

-H

Only displays the names of the relevant 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 FILE_1 FILE_2

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 to 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

File systems

mount OPTIONS DEVICE MOUNT_POINT

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 FILE_SYSTEM

Specify the file system: For Linux hard disks, this is commonly ext4, xfs, or btrfs.

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 needs to 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 MOUNT_POINT

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 relevant drive.

System commands

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

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 ??? 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.

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 PROCESS_NAME

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

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 functioning.

-cNUMBER

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

-iVALUE

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

host OPTIONS HOSTNAME SERVER

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

ssh OPTIONS [USER@]HOSTNAME COMMAND

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

Miscellaneous

passwd OPTIONS USER_NAME

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 USER_NAME

The su command makes it possible to log in under a different user name from a running session. Specify a user name 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 user name, you are prompted for the root password and change to the superuser (root). Use su - to start a login shell for a 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.

More information

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

Chapter 2. Bash and Bash scripts

Abstract

Today, many people use computers with a graphical user interface (GUI) like GNOME. Although GUIs offer many features, they're limited when performing automated task execution. Shells complement GUIs well, and this chapter gives an overview of some aspects of shells, in this case the Bash shell.

What is the shell?

Traditionally, the Linux shell is Bash (Bourne again Shell). When this chapter speaks about the shell it means Bash. There are more shells available (ash, csh, ksh, zsh, …), each employing different features and characteristics. If you need further information about other shells, search for shell in YaST.

Bash configuration files

A shell can be invoked as an:

  1. Interactive login shell.  This is used when logging in to a machine, invoking Bash with the --login option or when logging in to a remote machine with SSH.

  2. Ordinary interactive shell.  This is normally the case when starting xterm, konsole, gnome-terminal, or similar command-line interface (CLI) tools.

  3. Non-interactive shell.  This is invoked when invoking a shell script at the command line.

Depending on the type of shell you use, different configuration files will be read. The following tables show the login and non-login shell configuration files.

Table 2.1. Bash configuration files for login shells

File

Description

/etc/profile

Do not modify this file, otherwise your modifications may be destroyed during your next update!

/etc/profile.local

Use this file if you extend /etc/profile

/etc/profile.d/

Contains system-wide configuration files for specific programs

~/.profile

Insert user specific configuration for login shells here


Note that the login shell also sources the configuration files listed under Table 2.2, “Bash configuration files for non-login shells”.

Table 2.2. Bash configuration files for non-login shells

/etc/bash.bashrc

Do not modify this file, otherwise your modifications may be destroyed during your next update!

/etc/bash.bashrc.local

Use this file to insert your system-wide modifications for Bash only

~/.bashrc

Insert user specific configuration here


Additionally, Bash uses some more files:

Table 2.3. Special files for Bash

File

Description

~/.bash_history

Contains a list of all commands you have typed

~/.bash_logout

Executed when logging out

~/.alias

User defined aliases of frequently used commands. See man 1 alias for more details about defining aliases.


No-Login Shells

There are special shells that block users from logging into the system: /bin/false and /sbin/nologin. Both fail silently when the user attempts to log into the system. This was intended as a security measure for system users, though modern Linux operating systems have more effective tools for controlling system access, such as PAM and AppArmor.

The default on openSUSE LeapSUSE Linux Enterprise ServerSUSE Linux Enterprise DesktopSUSE Linux Enterprise Micro is to assign /bin/bash to human users, and /bin/false or /sbin/nologin to system users. The nobody user has /bin/bash for historical reasons, as it is a minimally-privileged user that used to be the default for system users. However, whatever little bit of security gained by using nobody is lost when multiple system users use it. It should be possible to change it to /sbin/nologin; the fastest way to test it is change it and see if it breaks any services or applications.

Use the following command to list which shells are assigned to all users, system and human users, in /etc/passwd. The output varies according to the services and users on your system:

tux@darkstar:~$ sort -t: -k 7 /etc/passwd | awk -F: '{print $1"\t" $7}' | column -t
tux               /bin/bash
nobody            /bin/bash
root              /bin/bash
avahi             /bin/false
chrony            /bin/false
dhcpd             /bin/false
dnsmasq           /bin/false
ftpsecure         /bin/false
lightdm           /bin/false
mysql             /bin/false
postfix           /bin/false
rtkit             /bin/false
sshd              /bin/false
tftp              /bin/false
unbound           /bin/false
bin               /sbin/nologin
daemon            /sbin/nologin
ftp               /sbin/nologin
lp                /sbin/nologin
mail              /sbin/nologin
man               /sbin/nologin
nscd              /sbin/nologin
polkitd           /sbin/nologin
pulse             /sbin/nologin
qemu              /sbin/nologin
radvd             /sbin/nologin
rpc               /sbin/nologin
statd             /sbin/nologin
svn               /sbin/nologin
systemd-coredump  /sbin/nologin
systemd-network   /sbin/nologin
systemd-timesync  /sbin/nologin
usbmux            /sbin/nologin
vnc               /sbin/nologin
wwwrun            /sbin/nologin
messagebus        /usr/bin/false
scard             /usr/sbin/nologin

The directory structure

The following table provides a short overview of the most important higher-level directories that you find on a Linux system. Find more detailed information about the directories and important subdirectories in the following list.

Table 2.4. Overview of a standard directory tree

Directory

Contents

/

Root directory—the starting point of the directory tree.

/bin

Essential binary files, such as commands that are needed by both the system administrator and normal users. Usually also contains the shells, such as Bash.

/boot

Static files of the boot loader.

/dev

Files needed to access host-specific devices.

/etc

Host-specific system configuration files.

/home

Holds the home directories of all users who have accounts on the system. However, root's home directory is not located in /home but in /root.

/lib

Essential shared libraries and kernel modules.

/media

Mount points for removable media.

/mnt

Mount point for temporarily mounting a file system.

/opt

Add-on application software packages.

/root

Home directory for the superuser root.

/sbin

Essential system binaries.

/srv

Data for services provided by the system.

/tmp

Temporary files.

/usr

Secondary hierarchy with read-only data.

/var

Variable data such as log files.

/windows

Only available if you have both Microsoft Windows* and Linux installed on your system. Contains the Windows data.


The following list provides more detailed information and gives some examples of which files and subdirectories can be found in the directories:

/bin

Contains the basic shell commands that may be used both by root and by other users. These commands include ls, mkdir, cp, mv, rm and rmdir. /bin also contains Bash, the default shell in openSUSE LeapSUSE Linux Enterprise ServerSUSE Linux Enterprise DesktopSUSE Linux Enterprise Micro.

/boot

Contains data required for booting, such as the boot loader, the kernel, and other data that is used before the kernel begins executing user-mode programs.

/dev

Holds device files that represent hardware components.

/etc

Contains local configuration files that control the operation of programs like the X Window System. The /etc/init.d subdirectory contains LSB init scripts that can be executed during the boot process.

/home/USERNAME

Holds the private data of every user who has an account on the system. The files located here can only be modified by their owner or by the system administrator. By default, your e-mail directory and personal desktop configuration are located here in the form of hidden files and directories, such as .gconf/ and .config.

Home directory in a network environment

If you are working in a network environment, your home directory may be mapped to a directory in the file system other than /home.

/lib

Contains the essential shared libraries needed to boot the system and to run the commands in the root file system. The Windows equivalent for shared libraries are DLL files.

/media

Contains mount points for removable media, such as CD-ROMs, flash disks, and digital cameras (if they use USB). /media generally holds any type of drive except the hard disk of your system. When your removable medium has been inserted or connected to the system and has been mounted, you can access it from here. taroth 060518: find out how the names of the drives are assigned to a medium!

/mnt

This directory provides a mount point for a temporarily mounted file system. root may mount file systems here.

/opt

Reserved for the installation of third-party software. Optional software and larger add-on program packages can be found here.

/root

Home directory for the root user. The personal data of root is located here.

/run

A tmpfs directory used by systemd and various components. /var/run is a symbolic link to /run.

/sbin

As the s indicates, this directory holds utilities for the superuser. /sbin contains the binaries essential for booting, restoring and recovering the system in addition to the binaries in /bin.

/srv

Holds data for services provided by the system, such as FTP and HTTP.

/tmp

This directory is used by programs that require temporary storage of files.

Cleaning up /tmp at boot time

Data stored in /tmp is not guaranteed to survive a system reboot. It depends, for example, on settings made in /etc/tmpfiles.d/tmp.conf.

/usr

/usr has nothing to do with users, but is the acronym for Unix system resources. The data in /usr is static, read-only data that can be shared among various hosts compliant with the Filesystem Hierarchy Standard (FHS). This directory contains all application programs including the graphical desktops such as GNOME and establishes a secondary hierarchy in the file system. /usr holds several subdirectories, such as /usr/bin, /usr/sbin, /usr/local, and /usr/share/doc.

/usr/bin

Contains generally accessible programs.

/usr/sbin

Contains programs reserved for the system administrator, such as repair functions.

/usr/local

In this directory the system administrator can install local, distribution-independent extensions.

/usr/share/doc

Holds various documentation files and the release notes for your system. In the manual subdirectory find an online version of this manual. If more than one language is installed, this directory may contain versions of the manuals for different languages.

Under packages find the documentation included in the software packages installed on your system. For every package, a subdirectory /usr/share/doc/packages/PACKAGENAME is created that often holds README files for the package and sometimes examples, configuration files or additional scripts.

If HOWTOs are installed on your system /usr/share/doc also holds the howto subdirectory in which to find additional documentation on many tasks related to the setup and operation of Linux software.

/var

Whereas /usr holds static, read-only data, /var is for data which is written during system operation and thus is variable data, such as log files or spooling data. For an overview of the most important log files you can find under /var/log/, refer to ???.

/windows

Only available if you have both Microsoft Windows and Linux installed on your system. Contains the Windows data available on the Windows partition of your system. Whether you can edit the data in this directory depends on the file system your Windows partition uses. If it is FAT32, you can open and edit the files in this directory. For NTFS, openSUSE LeapSUSE Linux Enterprise ServerSUSE Linux Enterprise DesktopSUSE Linux Enterprise Micro also includes write access support. However, the driver for the NTFS-3g file system has limited functionality.

Writing shell scripts

Shell scripts provide a convenient way to perform a wide range of tasks: collecting data, searching for a word or phrase in a text and other useful things. The following example shows a small shell script that prints a text:

Example 2.1. A shell script printing a text

#!/bin/sh 1
# Output the following line: 2
echo "Hello World" 3

1

The first line begins with the Shebang characters (#!) which indicate that this file is a script. The interpreter, specified after the Shebang, executes the script. In this case, the specified interpreter is /bin/sh.

2

The second line is a comment beginning with the hash sign. We recommend that you comment difficult lines. With proper commenting, you can remember the purpose and function of the line. Also, other readers will hopefully understand your script. Commenting is considered good practice in the development community.

3

The third line uses the built-in command echo to print the corresponding text.


Before you can run this script, there are a few prerequisites:

  1. Every script should contain a Shebang line (as in the example above). If the line is missing, you need to call the interpreter manually.

  2. You can save the script wherever you want. However, it is a good idea to save it in a directory where the shell can find it. The search path in a shell is determined by the environment variable PATH. Usually a normal user does not have write access to /usr/bin. Therefore it is recommended to save your scripts in the users' directory ~/bin/. The above example gets the name hello.sh.

  3. The script needs executable permissions. Set the permissions with the following command:

    tux@darkstar:~$ chmod +x ~/bin/hello.sh

If you have fulfilled all of the above prerequisites, you can execute the script in the following ways:

  1. As absolute path.  The script can be executed with an absolute path. In our case, it is ~/bin/hello.sh.

  2. Everywhere.  If the PATH environment variable contains the directory where the script is located, you can execute the script with hello.sh.

Redirecting command events

Each command can use three channels, either for input or output:

  • Standard output.  This is the default output channel. Whenever a command prints something, it uses the standard output channel.

  • Standard input.  If a command needs input from users or other commands, it uses this channel.

  • Standard error.  Commands use this channel for error reporting.

To redirect these channels, there are the following possibilities:

Command > File

Saves the output of the command into a file, an existing file will be deleted. For example, the ls command writes its output into the file listing.txt:

tux@darkstar:~$ ls > listing.txt
Command >> File

Appends the output of the command to a file. For example, the ls command appends its output to the file listing.txt:

tux@darkstar:~$ ls >> listing.txt
Command < File

Reads the file as input for the given command. For example, the read command reads in the content of the file into the variable:

tux@darkstar:~$ read a < foo
Command1 | Command2

Redirects the output of the left command as input for the right command. For example, the cat command outputs the content of the /proc/cpuinfo file. This output is used by grep to filter only those lines which contain cpu:

tux@darkstar:~$ cat /proc/cpuinfo | grep cpu

Every channel has a file descriptor: 0 (zero) for standard input, 1 for standard output and 2 for standard error. It is allowed to insert this file descriptor before a < or > character. For example, the following line searches for a file starting with foo, but suppresses its errors by redirecting it to /dev/null:

tux@darkstar:~$ find / -name "foo*" 2>/dev/null

Using aliases

An alias is a shortcut definition of one or more commands. The syntax for an alias is:

alias NAME=DEFINITION

For example, the following line defines an alias lt that outputs a long listing (option -l), sorts it by modification time (-t), and prints it in reverse sorted order (-r):

tux@darkstar:~$ alias lt='ls -ltr'

To view all alias definitions, use alias. Remove your alias with unalias and the corresponding alias name.

Using variables in Bash

A shell variable can be global or local. Global variables, or environment variables, can be accessed in all shells. In contrast, local variables are visible in the current shell only.

To view all environment variables, use the printenv command. If you need to know the value of a variable, insert the name of your variable as an argument:

tux@darkstar:~$ printenv PATH

A variable, be it global or local, can also be viewed with echo:

tux@darkstar:~$ echo $PATH

To set a local variable, use a variable name followed by the equal sign, followed by the value:

tux@darkstar:~$ PROJECT="SLED"

Do not insert spaces around the equal sign, otherwise you get an error. To set an environment variable, use export:

tux@darkstar:~$ export NAME="tux"

To remove a variable, use unset:

tux@darkstar:~$ unset NAME

The following table contains some common environment variables which can be used in you shell scripts:

Table 2.5. Useful environment variables

HOME

the home directory of the current user

HOST

the current host name

LANG

when a tool is localized, it uses the language from this environment variable. English can also be set to C

PATH

the search path of the shell, a list of directories separated by colon

PS1

specifies the normal prompt printed before each command

PS2

specifies the secondary prompt printed when you execute a multi-line command

PWD

current working directory

USER

the current user


Using argument variables

For example, if you have the script foo.sh you can execute it like this:

tux@darkstar:~$ foo.sh "Tux Penguin" 2000 

To access all the arguments which are passed to your script, you need positional parameters. These are $1 for the first argument, $2 for the second, and so on. You can have up to nine parameters. To get the script name, use $0.

The following script foo.sh prints all arguments from 1 to 4:

#!/bin/sh
echo \"$1\" \"$2\" \"$3\" \"$4\"

If you execute this script with the above arguments, you get:

"Tux Penguin" "2000" "" ""

Using variable substitution

Variable substitutions apply a pattern to the content of a variable either from the left or right side. The following list contains the possible syntax forms:

${VAR#pattern}

removes the shortest possible match from the left:

tux@darkstar:~$ file=/home/tux/book/book.tar.bz2
tux@darkstar:~$ echo ${file#*/}
home/tux/book/book.tar.bz2
${VAR##pattern}

removes the longest possible match from the left:

tux@darkstar:~$ file=/home/tux/book/book.tar.bz2
tux@darkstar:~$ echo ${file##*/}
book.tar.bz2
${VAR%pattern}

removes the shortest possible match from the right:

tux@darkstar:~$ file=/home/tux/book/book.tar.bz2
tux@darkstar:~$ echo ${file%.*}
/home/tux/book/book.tar
${VAR%%pattern}

removes the longest possible match from the right:

tux@darkstar:~$ file=/home/tux/book/book.tar.bz2
tux@darkstar:~$ echo ${file%%.*}
/home/tux/book/book
${VAR/pattern_1/pattern_2}

substitutes the content of VAR from the PATTERN_1 with PATTERN_2:

tux@darkstar:~$ file=/home/tux/book/book.tar.bz2
tux@darkstar:~$ echo ${file/tux/lucas}
/home/lucas/book/book.tar.bz2

Grouping and combining commands

Shells allow you to concatenate and group commands for conditional execution. Each command returns an exit code which determines the success or failure of its operation. If it is 0 (zero) the command was successful, everything else marks an error which is specific to the command.

The following list shows, how commands can be grouped:

Command1 ; Command2

executes the commands in sequential order. The exit code is not checked. The following line displays the content of the file with cat and then prints its file properties with ls regardless of their exit codes:

tux@darkstar:~$ cat filelist.txt ; ls -l filelist.txt
Command1 && Command2

runs the right command, if the left command was successful (logical AND). The following line displays the content of the file and prints its file properties only, when the previous command was successful (compare it with the previous entry in this list):

tux@darkstar:~$ cat filelist.txt && ls -l filelist.txt
Command1 || Command2

runs the right command, when the left command has failed (logical OR). The following line creates only a directory in /home/lucas/bar when the creation of the directory in /home/tux/foo has failed:

tux@darkstar:~$ mkdir /home/tux/foo || mkdir /home/lucas/bar
funcname(){ ... }

creates a shell function. You can use the positional parameters to access its arguments. The following line defines the function hello to print a short message:

tux@darkstar:~$ hello() { echo "Hello $1"; }

You can call this function like this:

tux@darkstar:~$ hello Tux

which prints:

Hello Tux

Working with common flow constructs

To control the flow of your script, a shell has while, if, for and case constructs.

The if control command

The if command is used to check expressions. For example, the following code tests whether the current user is Tux:

if test $USER = "tux"; then
echo "Hello Tux."
else
echo "You are not Tux."
fi

The test expression can be as complex or simple as possible. The following expression checks if the file foo.txt exists:

if test -e /tmp/foo.txt ; then
echo "Found foo.txt"
fi

The test expression can also be abbreviated in square brackets:

if [ -e /tmp/foo.txt ] ; then
echo "Found foo.txt"
fi

Find more useful expressions at https://bash.cyberciti.biz/guide/If..else..fi.

Creating loops with the for command

The for loop allows you to execute commands to a list of entries. For example, the following code prints some information about PNG files in the current directory:

for i in *.png; do
ls -l $i
done

More information

Important information about Bash is provided in the man pages man bash. More about this topic can be found in the following list:

Appendix A. GNU free documentation license

Table of Contents

Copyright (C) 2000, 2001, 2002 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

0. PREAMBLE

The purpose of this License is to make a manual, textbook, or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or non-commercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.

This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.

We have designed this License to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.

1. APPLICABILITY AND DEFINITIONS

This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.

A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.

A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.

The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.

The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.

A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transparent" is called "Opaque".

Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only.

The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text.

A section "Entitled XYZ" means a named sub-unit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition.

The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.

2. VERBATIM COPYING

You may copy and distribute the Document in any medium, either commercially or non-commercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.

You may also lend copies, under the same conditions stated above, and you may publicly display copies.

3. COPYING IN QUANTITY

If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.

If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.

If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.

It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.

4. MODIFICATIONS

You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:

  1. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission.

  2. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement.

  3. State on the Title page the name of the publisher of the Modified Version, as the publisher.

  4. Preserve all the copyright notices of the Document.

  5. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices.

  6. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below.

  7. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice.

  8. Include an unaltered copy of this License.

  9. Preserve the section Entitled "History", Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence.

  10. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission.

  11. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein.

  12. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles.

  13. Delete any section Entitled "Endorsements". Such a section may not be included in the Modified Version.

  14. Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title with any Invariant Section.

  15. Preserve any Warranty Disclaimers.

If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles.

You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties--for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.

You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.

The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.

5. COMBINING DOCUMENTS

You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.

The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.

In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements".

6. COLLECTIONS OF DOCUMENTS

You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.

You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.

7. AGGREGATION WITH INDEPENDENT WORKS

A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.

If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.

8. TRANSLATION

Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.

If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.

9. TERMINATION

You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy, modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.

10. FUTURE REVISIONS OF THIS LICENSE

The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/.

Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation.

ADDENDUM: How to use this License for your documents
Copyright (c) YEAR YOUR NAME.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.2
or any later version published by the Free Software Foundation;
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
A copy of the license is included in the section entitled “GNU
Free Documentation License”.

If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the “with...Texts.” line with this:

with the Invariant Sections being LIST THEIR TITLES, with the
Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.

If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation.

If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.