13 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 KDE or GNOME.
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 openSUSE® Leap 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 14, Bash and Bash scripts.
13.1 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@linux:~>
Your login. | |
The hostname of your computer. | |
Path to the current directory. Directly after login, the current
directory usually is your home directory, indicated by the
|
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.
13.2 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, <— (Backspace), Del, and Space. You can correct typing errors or add options. The command is not executed until you press Enter.
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.
13.2.1 Using commands without options #
In Section 13.6.1, “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:
>ls bin Desktop Documents public_html tux.txt>
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.
13.2.2 Using commands with options #
A better way to get more details about the contents of a
directory is using the ls command with a string of
options. Options modify the way a command works so that you can get it
to 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):
>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>
This output shows the following information about each object:
drwxr-xr-x1 12 tux3 users4 485 2006-06-23 16:086 bin7
Type of object and access permissions. For further information, refer to Section 13.6.1, “Permissions for user, group and others”. | |
Number of hard links to this file. | |
Owner of the file or directory. For further information, refer to Section 13.6.1, “Permissions for user, group and others”. | |
Group assigned to the file or directory. For further information, refer to Section 13.6.1, “Permissions for user, group and others”. | |
File size in bytes. | |
Date and time of the last change. | |
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.
13.2.3 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. |
|
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. |
13.3 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/-hoptionIf you only want to look up the options of a certain command, try entering the command followed by a space and
--help. This--helpoption exists for many commands. For example,ls--helpdisplays all the options for thelscommand.- 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
manfollowed 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
mancommand, useman man.- Info pages
Info pages usually provide even more information about commands. To view the info page for a certain command, enter
infofollowed 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.
13.4 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 namedfile.txtin yourDocumentsdirectory 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 pathfile.txtin yourDocumentsdirectory is:Documents/file.txt
However, if your working directory is
/home/tux/Musicinstead, 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.
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, usels~. To list the contents of another user's home directory, enterls~USERNAME(or course, this will only work if you have permission to view the contents, see Section 13.6, “File access permissions”). For example, enteringls ~tuxwould list the contents of the home directory of a user namedtux. 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/homebut 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 enteringcdwithout any options.When using relative paths, refer to the current directory with a dot (
.). This is mainly useful for commands such ascpormvby 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, entercd .., to go up two levels from the current directory entercd ../..etc.
To apply your knowledge, find some examples below. They address basic tasks you may want to execute with files or folders using Bash.
13.4.1 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.
From your home directory create a subdirectory in
/tmp:
Enter
>mkdir /tmp/testmkdirstands for “make directory”. This command creates a new directory namedtestin the/tmpdirectory. In this case, you are using an absolute path to create thetestdirectory.To check what happened, now enter
>ls -l /tmpThe new directory
testshould appear in the list of contents of the/tmpdirectory.Switch to the newly created directory with
>cd /tmp/test
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.
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.
To list the contents of your home directory, enter
>ls -l ~It should contain a subdirectory called
Documentsby default. If not, create this subdirectory with themkdircommand you already know:>mkdir ~/DocumentsTo create a new, empty file named
myfile.txtin theDocumentsdirectory, enter>touch ~/Documents/myfile.txtUsually, the
touchcommand updates the modification and access date for an existing file. If you usetouchwith a filename which does not exist in your target directory, it creates a new file.Enter
>ls -l ~/DocumentsThe new file should appear in the list of contents.
To copy the newly created file, enter
>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.txtfrom theDocumentssubdirectory to the current directory,/tmp/test, without changing the name of the file.Check the result by entering
>ls -lThe file
myfile.txtshould appear in the list of contents for/tmp/test.
Now suppose you want to rename myfile.txt into
tuxfile.txt. Finally you decide to remove the
renamed file and the test subdirectory.
To rename the file, enter
>mv myfile.txt tuxfile.txtTo check what happened, enter
>ls -lInstead of
myfile.txt,tuxfile.txtshould appear in the list of contents.mvstands formoveand is used with two options: the first option specifies the source, the second option specifies the target of the operation. You can usemveitherto rename a file or a directory,
to move a file or directory to a new location or
to do both in one step.
Coming to the conclusion that you do not need the file any longer, you can delete it by entering
>rm tuxfile.txtBash deletes the file without any confirmation.
Move up one level with
cd ..and check with>ls -l testif the
testdirectory is empty now.If yes, you can remove the
testdirectory by entering>rmdir test
13.5 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 YaST requires
root permissions.
13.5.1 Using su #
In order to temporarily become root in a shell, proceed as
follows:
Enter
su. You are prompted for therootpassword.Enter the password. If you mistyped the
rootpassword, the shell displays a message. In this case, you have to re-entersubefore retyping the password. If your password is correct, a hash symbol#appears at the end of the prompt, signaling that you are acting asrootnow.Execute your task. For example, transfer ownership of a file to a new user which only
rootis allowed to do:>chownwilberkde_quick.xmlAfter having completed your tasks as
root, switch back to your normal user account. To do so, enter>exitThe hash symbol disappears and you are acting as “normal” user again.
13.5.2 Using sudo #
Alternatively, you can also use sudo (superuser
“do”) to execute some tasks which normally are for
roots 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. In openSUSE, sudo requires the root password by default
(if not configured otherwise by your system administrator).
For users, sudo is convenient as it prevents you from switching accounts
twice (to root and back again). To change the ownership of a file
using sudo, only one command is necessary instead of three:
>sudochownwilberkde_quick.xml
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.
13.6 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 Book “Security and Hardening Guide”, Chapter 19 “Access control lists in Linux”. 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. 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.
13.6.1 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.
-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 |
|
|
|
|
|
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 13.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.
13.6.2 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:
|
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
|
|
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.
13.6.3 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 Section 13.6, “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.
13.6.3.1 Examples for changing access permissions and ownership #
The following example shows the output of an ls
-l command in a shell.
-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.
Suppose you are tux and want to
modify the access permissions to your files:
If you want to grant the
usersgroup also write access tokde-start.xml, enter>chmod g+w kde-start.xmlTo grant the
usersgroup and other users write access tokde-start.xml, enter>chmod go+w kde-start.xmlTo remove write access for all users, enter
>chmod -w kde-start.xmlIf 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
tuxdoes not have write access to the file without first reestablishing write permissions.To prohibit the
usersgroup and others to change into the directorylocal, enter>chmod go-x localTo grant others write permissions for two files, for
kde_quick.xmlandgnome_quick.xml, enter>chmod o+w kde_quick.xml gnome_quick.xml
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:
Enter the username and password for
root.Enter
#chownwilberkde_quick.xmlCheck what happened with
>ls -l kde_quick.xmlYou should get the following output:
-rw-r--r-- 1 wilber users 47896 2006-06-21 09:46 kde_quick.xml
If the ownership is set according to your wishes, switch back to your normal user account.
13.7 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:
>(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.
13.7.1 Examples for using history, completion and wild cards #
The following examples illustrate how to make use of these convenient features of Bash.
If you already did the example Section 13.4.1, “Examples for working with files and directories”, your shell buffer should be filled with commands which you can retrieve using the history function.
Press ↑ repeatedly until
cd ~appears.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,
DocumentsandDesktop.Type
cd Dand press →|.Nothing happens since Bash cannot identify to which one of the subdirectories you want to change.
Press →| again to see the list of possible choices:
>cd DDesktop/ Documents/ Downloads/>cd DThe 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.
You can now execute the command with Enter.
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.
First, create some test files in your home directory:
Use the
touchcommand to create several (empty) files with different file extensions, for example.pdf,.xmland.jpg.You can do this consecutively (do not forget to use the Bash history function) or with only one
touchcommand: simply add several filenames separated by a space.Create at least two files that have the same file extension, for example
.html.To create several “versions” of one file, enter
>touch myfile{1..5}.txtThis command creates five consecutively numbered files:
myfile1.txt, …,myfile5.txt.List the contents of the directory. It should look similar to this:
>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
With wild cards, select certain subsets of the files according to various criteria:
To list all files with the
.htmlextension, enter>ls -l *.htmlTo list all “versions” of
myfile.txt, enter>ls -l myfile?.txtNote 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 namedmyfile10.txtyou must to use the*wild card to view all versions ofmyfile.txt(or add another question mark, so your string looks likemyfile??.txt).To remove, for example, version 1-3 and version 5 of
myfile.txt, enter>rm myfile[1-3,5].txtCheck the result with
>ls -lOf all
myfile.txtversions onlymyfile4.txtshould 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.
rm commands
Wild cards 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 wild card string with
ls instead of rm first.
13.8 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.
13.8.1 Example: editing with vi #
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.
To create and open a new file with vi, enter
>vi textfile.txtBy default, vi opens in command mode in which you cannot enter text.
Press I to switch to insert mode. The bottom line changes and indicates that you now can insert text.
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.
In the insert mode, you can edit the text with the arrow keys and with Del.
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.
To leave vi and save your changes, type
wq(wforwrite;qforquit) and press Enter. If you want to save the file under a different name, typew FILENAMEand press Enter.To leave vi without saving, type
q!instead and press Enter.
13.9 Searching for files or contents #
Bash offers you several commands to search for files and to search for the contents of files:
findWith
find, search for a file in a given directory. The first argument specifies the directory in which to start the search. The option-namemust be followed by a search string, which may also include wild cards. Unlikelocate, which uses a database,findscans the actual directory.grepThe
grepcommand finds a specific search string in the specified text files. If the search string is found, the command displays the line in whichsearchstringwas found, along with the filename. If desired, use wild cards to specify filenames.
13.9.1 Examples for searching #
To search your home directory for all occurrences of filenames that contain the file extension
.txt, use:>find ~ -name '*.txt' -printTo search a directory (in this case, your home directory) for all occurrences of files which contain, for example, the word
music, use:>grep music ~/*grepis case-sensitive by default. Hence, with the command above you will not find any files containingMusic.To ignore case, use the-ioption.To use a search string which consists of more than one word, enclose the string in double quotation marks, for example:
>grep "music is great" ~/*
13.10 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.
headWith
headyou can view the first lines of a text file. If you do not specify the command any further,headshows the first 10 lines of a text file.tailThe
tailcommand is the counterpart ofhead. If you usetailwithout 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.lessWith
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.moreInstead of
less, you can also use the older programmore. It has basically the same function—however, it is less convenient because it does not allow you to scroll backward. Use Space to move forward. When you reach the end of the document, the viewer closes automatically.catThe
catcommand displays the contents of a file, printing the entire contents to the screen without interruption. Ascatdoes not allow you to scroll it is not very useful as viewer but it is rather often used in combination with other commands.
13.11 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.
13.11.1 Examples for redirection and pipe #
To write the output of a command like
lsto a file, enter>ls -l > filelist.txtThis creates a file named
filelist.txtthat contains the list of contents of your current directory as generated by thelscommand.However, if a file named
filelist.txtalready exists, this command overwrites the existing file. To prevent this, use>>instead of >. Entering>ls -l >> filelist.txtsimply appends the output of the
lscommand to an already existing file namedfilelist.txt. If the file does not exist, it is created.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:
>sort < filelist.txtThis will force the
sortcommand to get its input from the contents offilelist.txt. The result is shown on the screen. Of course, you can also write the result into another file, using a combination of redirections:>sort < filelist.txt > sorted_filelist.txtIf a command generates a lengthy output, like
ls-lmay do, it may be useful to pipe the output to a viewer likelessto be able to scroll through the pages. To do so, enter>ls -l | lessThe list of contents of the current directory is shown in
less.The pipe is also often used in combination with the
grepcommand 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 usertux, enter>ls -l | grep tux
13.12 Starting programs and handling processes #
As you have seen in Section 13.8, “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 KDE or GNOME, simply run
okular ~/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:
> 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:
> 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:
> 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
> kill 30187This 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
(%):
> kill %JOB_NUMBER
If kill does not help—as is sometimes the case
for “runaway” programs—try
> kill -9 PIDThis 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 Book “System Analysis and Tuning Guide”, Chapter 2 “System monitoring utilities”, Section 2.3 “Processes”.
13.13 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 iscpio.Compressors, which losslessly make a file smaller. The most commonly used compressors are
gzipandbzip2.
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:
Open a shell.
Use
cdto change to your home directory where thetestdirectory is located.Compress the file with:
>tar -cvf testarchive.tar testThe
-coption creates the archive, making it a file as directed by-f. The-voption lists the files as they are processed.The
testdirectory with all its files and directories has remained unchanged on your hard disk.View the contents of the archive file with:
>tar -tf testarchive.tarTo unpack the archive, use:
>tar -xvf testarchive.tarIf 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.
For this example, reuse the archive
testarchive.tarfrom Procedure 13.8, “Archiving files”.To compress the archive, use:
>gzip testarchive.tarWith
ls, now see that the filetestarchive.taris no longer there and that the filetestarchive.tar.gzhas been created instead.As an alternative, use
bzip2 testarchive.tarwhich works analogously but provides somewhat better compression.Now decompress and unarchive the file again:
This can be done in two steps by first decompressing and then unarchiving the file:
>gzip --decompress testarchive.tar.gz>tar -xvf testarchive.tarYou can also decompress and unarchive in one step:
>tar -xvf testarchive.tar
With
ls, you can see that a newtestdirectory has been created with the same contents as yourtestdirectory in your home directory.
13.14 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.
13.14.1 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.
13.14.1.1 File administration #
lsOPTIONS FILESIf you run
lswithout any additional parameters, the program lists the contents of the current directory in short form.-lDetailed list
-aDisplays hidden files
cpOPTIONS SOURCE TARGETCopies
sourcetotarget.- -i
Waits for confirmation, if necessary, before an existing
targetis overwritten- -r
Copies recursively (includes subdirectories)
mvOPTIONS SOURCE TARGETCopies
sourcetotargetthen deletes the originalsource.- -b
Creates a backup copy of the
sourcebefore moving- -i
Waits for confirmation, if necessary, before an existing
targetfileis overwritten
rmOPTIONS FILESRemoves the specified files from the file system. Directories are not removed by
rmunless the option-ris used.-rDeletes any existing subdirectories
-iWaits for confirmation before deleting each file
lnOPTIONS SOURCE TARGETCreates an internal link from source to target. Normally, such a link points directly to source on the same file system. However, if
lnis executed with the-soption, it creates a symbolic link that only points to the directory in whichsourceis located, enabling linking across file systems.- -s
Creates a symbolic link
cdOPTIONS DIRECTORYChanges the current directory.
cdwithout any parameters changes to the user's home directory.mkdirOPTIONS DIRECTORYCreates a new directory.
rmdirOPTIONS DIRECTORYDeletes the specified directory if it is already empty.
chownOPTIONSUSER_NAME[:GROUP]FILESTransfers ownership of a file to the user with the specified user name.
-RChanges files and directories in all subdirectories
chgrpOPTIONS GROUP_NAME FILESTransfers the group ownership of a given
fileto 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.chmodOPTIONS MODE FILESChanges the access permissions.
The
modeparameter has three parts:group,access, andaccess type.groupaccepts the following characters:- u
User
- g
Group
- o
Others
For
access, grant access with+and deny it with-.The
access typeis 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.
gzipPARAMETERS FILESThis program compresses the contents of files using complex mathematical algorithms. Files compressed in this way are given the extension
.gzand need to be uncompressed before they can be used. To compress several files or even entire directories, use thetarcommand.- -d
Decompresses the packed gzip files so they return to their original size and can be processed normally (like the command
gunzip)
tarOPTIONS ARCHIVE FILEStarputs one or more files into an archive. Compression is optional.taris a quite complex command with several options available. The most frequently used options are:-fWrites the output to a file and not to the screen as is usually the case
-cCreates a new TAR archive
-rAdds files to an existing archive
-tOutputs the contents of an archive
-uAdds files, but only if they are newer than the files already contained in the archive
-xUnpacks files from an archive (extraction)
-zPacks the resulting archive with
gzip-jCompresses the resulting archive with
bzip2-vLists files processed
The archive files created by
tarend with.tar. If the TAR archive was also compressed usinggzip, the ending is.tgzor.tar.gz. If it was compressed usingbzip2, the ending is.tar.bz2.findOPTIONSWith
find, search for a file in a given directory. The first argument specifies the directory in which to start the search. The option-namemust be followed by a search string, which may also include wild cards. Unlikelocate, which uses a database,findscans the actual directory.
13.14.1.2 Commands to access file contents #
fileOPTIONS FILESIn Linux, files can have a file extensions but do not need to have one. The
filedetermines the file type of a given file. With the output offile, you can then choose an appropriate application with which to open the file.- -z
Tries to look inside compressed files
catOPTIONS FILESThe
catcommand displays the contents of a file, printing the entire contents to the screen without interruption.- -n
Numbers the output on the left margin
lessOPTIONS FILESThis 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.
grepOPTIONS SEARCH_STRING FILESThe
grepcommand 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.-iIgnores case
-HOnly displays the names of the relevant files, but not the text lines
-nAdditionally displays the numbers of the lines in which it found a hit
-lOnly lists the files in which
searchstringdoes not occur
diffOPTIONS FILE_1 FILE_2The
diffcommand 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.-qOnly reports whether the two files differ
-uProduces a “unified” diff, which makes the output more readable
13.14.1.3 File systems #
mountOPTIONS DEVICE MOUNT_POINTThis 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.
-rMount read-only
-t FILE_SYSTEMSpecify the file system: For Linux hard disks, this is commonly
ext4,xfs, orbtrfs.
For hard disks not defined in the file
/etc/fstab, the device type must also be specified. In this case, onlyrootcan mount it. If the file system needs to also be mounted by other users, enter the optionuserin the appropriate line in the/etc/fstabfile (separated by commas) and save this change. Further information is available in themount(1)man page.umountOPTIONS MOUNT_POINTThis 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
rootis allowed to run the commandsmountandumount. To enable other users to run these commands, edit the/etc/fstabfile to specify the optionuserfor the relevant drive.
13.14.2 System commands #
The following section lists a few of the most important commands needed for retrieving system information and controlling processes and the network.
13.14.2.1 System information #
dfOPTIONS DIRECTORYThe
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.-hShows the number of occupied blocks in gigabytes, megabytes, or kilobytes—in human-readable format
-TType of file system (ext2, nfs, etc.)
duOPTIONS PATHThis command, when executed without any parameters, shows the total disk space occupied by files and subdirectories in the current directory.
-aDisplays the size of each individual file
-hOutput in human-readable form
-sDisplays only the calculated total size
freeOPTIONSThe command
freedisplays information about RAM and swap space usage, showing the total and the used amount in both categories. See Book “Reference”, Chapter 15 “Special system features”, Section 15.1.7 “Thefreecommand” for more information.-bOutput in bytes
-kOutput in kilobytes
-mOutput in megabytes
dateOPTIONSThis 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.
13.14.2.2 Processes #
topOPTIONStopprovides a quick overview of the currently running processes. Press H to access a page that briefly explains the main options for customizing the program.psOPTIONS PROCESS_IDIf 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
killOPTIONS PROCESS_IDUnfortunately, 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
killcommand, specifying the respective process ID (seetopandps).killsends 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
killallOPTIONS PROCESS_NAMEThis command is similar to
kill, but uses the process name (instead of the process ID) as an argument, ending all processes with that name.
13.14.2.3 Network #
pingOPTIONS HOSTNAME_OR_IP_ADDRESSThe
pingcommand 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,pingdisplays a message to that effect, which indicates that the network link is functioning.-cNUMBERDetermines the total number of packages to send and ends after they have been dispatched (by default, there is no limitation set)
-fflood ping: sends as many data packages as possible; a popular means, reserved for
root, to test networks-iVALUESpecifies the interval between two data packages in seconds (default: one second)
hostOPTIONS HOSTNAME SERVERThe domain name system resolves domain names to IP addresses. With this tool, send queries to name servers (DNS servers).
sshOPTIONS[USER@]HOSTNAMECOMMANDSSH 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.
13.14.2.4 Miscellaneous #
passwdOPTIONS USER_NAMEUsers may change their own passwords at any time using this command. The administrator
rootcan use the command to change the password of any user on the system.suOPTIONS USER_NAMEThe
sucommand 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 fromroot, becauserootis authorized to assume the identity of any user. When using the command without specifying a user name, you are prompted for therootpassword and change to the superuser (root). Usesu -to start a login shell for a different user.haltOPTIONSTo avoid loss of data, you should always use this program to shut down your system.
rebootOPTIONSDoes the same as
haltexcept the system performs an immediate reboot.clearThis command cleans up the visible area of the console. It has no options.
13.14.3 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.