Web Analytics

See also ebooksgratis.com: no banners, no cookies, totally FREE.

CLASSICISTRANIERI HOME PAGE - YOUTUBE CHANNEL
Privacy Policy Cookie Policy Terms and Conditions
Appunti di informatica libera

[next] [previous] [top] [last] [indice generale] [violazione GPL] [translators] [docinfo] [indice analitico] [volume] [part]


Chapter 589.   Practical exercises

(1)

GNU/Linux is not an ``easy'' operating system; however the installation of most existing distributions is sufficiently simple.

This chapter collects some practical exercises that should be done by anyone who has not experiences with the Unix or similar operating systems. They are meant to be used on an isolated computer because they do not include network functionality.

If you cannot access an available working GNU/Linux system, you are advised to at least read the chapter, even if you cannot do immediately practical tests. The examples are shown in a way that is similar to the interaction that actually happens between the user and the operating system. (2)

589.1   System features

The proposed exercises assume that you have available a system configured as follows:

589.2   System access and activity termination

In order to use the system, it is necessary to use an identification procedure. To be identified and accepted, one should be registered as a user represented in practice by a user name and a password. It is useful to remember that the use of upper and lower case letters is not equivalent. In the proposed example we assume that the name is bloggs, written with all lower case letters, and the password billy.

We start by entering a wrong user name.

login: blogs[Enter]

Even if the wrong name does not exist, the user is requested to enter also the password. This is a security feature in order to avoid giving information about the existence of a given user-name.

Password: billy[Enter]

Login incorrect

Naturally, the entry of the word billy, as a password, is not presented on the screen. This happens to avoid that somebody might read it and use the information for negative purposes.

If anything is wrong in the access phase (login), one has to start again. We assume that the second time the operation is done correctly.

login: bloggs[Enter]

Password: billy[Enter]

Last login: Sun Nov 11 10:45:11 on tty1

Generally, after having correctly performed the access procedure, one gets the information about the last access made by the same user. This allows to check in a simple way that nobody else has used the system with the same user name.

Later the system presents the prompt of the shell (The prompt) means that one is allowed to enter commands.

$

The prompt, represented in this example by the dollar symbol, can be more or less complex, with information considered useful for the user. Actually it is something that every user can configure as he prefers, but this is beyond the purpose of these exercises.

Usually and traditionally, the prompt terminates with a symbol that changes according to the importance of the user: if it is the root the symbol # is used, otherwise the dollar as in our example.

589.2.1   Identity change

When the same person has more than one user name, it may be useful or necessary to act under a different identity than that used normally. This is the typical situation of the system administrator: for the operations different from the administration he should access the system as a regular user, whereas in the other cases he must use the privileges reserved to the root user.

This can be done in two different ways: by terminating the work session and by entering with another user-name, or by using the command su which allows to change the privileges temporaraly.

su brown[Enter]

Password: ciao[Enter]

If the password is correct, one gets the privileges and identity of the entered user, otherwise nothing changes.

589.2.2   Virtual consoles

A GNU/Linux system, installed normally, allows to use different virtual consoles (usually six are available) that can be accesed by using the combination [Alt+Fn] (where n is a number from one to six).

When a user is already signed on, he cam start a new work session from another console.

[Alt+F2]

In this way, one moves to the second virtual console and can sign on as a different user. The activities performed in the various virtual consoles are independent, as if they were made through physically distinct terminals.

Before continuing with the exercises, you should go back to the previous virtual console.

[Alt+F1]

589.2.3   Who am I?

When the same person can access the system with different user names, it might be necessary to check the identity currently used. In the following examples we assume that the command su brown discussed above has been successful.

whoami[Enter]

brown

The command whoami (``who am I'') allows to determine the current user identity.

logname[Enter]

bloggs

The command logname allows to determine the user identity used for the initial access.

589.2.4   Terminating a work session

To terminate a work session it is sufficient to stop the activity of the shell, i.e. the program that shows the prompt.

The situation is that of the previous examples, the current user was brown after a command su, whereas before that the user had the identity bloggs.

whoami[Enter]

brown

exit[Enter]

In this case, the command exit that has just been executed takes us back to the situation before the execution of su

whoami[Enter]

bloggs

The command exit closes the last shell and therefore closes down the system access.

exit[Enter]

login:

The system represents the login identification request of the access procedure.

589.2.5   Shutting down

The computer can be switched off only after stopping the system, generally done by using the command shutdown that can be used only by the user root.

login: root[Enter]

Password: ameba[Enter]

shutdown -h now[Enter]

System is going down NOW!!
...

The system halt procedure is started to gradually stop all active services. Finally the messege below is displayed

System halted

or

Power down

according to the version of the kernel. After this message, it is possible to switch off and restart the computer.

If you prefer to use shutdown after the command su in order to avoid exiting and doing a new login, it is possible to do as follows.

su[Enter]

When the command su is used without arguments, it is assumed implecitely that one wants to use the root user identity.

Password: ameba[Enter]

shutdown -h now[Enter]

589.2.6   Becoming a temporary administrator

The command su, just presented, when it is used to take the privileges of the root user, makes only a limited environment available (we refer to the environment variables and their content). For example, if the user bloggs becomes temporarely root, the content of the environment variable PATH changes in a strange way:

whoami[Enter]

bloggs

echo $PATH[Enter]

/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/games:/opt/prova/bin:/bin:./bin

su[Enter]

Password: ameba[Enter]

whoami[Enter]

root

echo $PATH[Enter]

/sbin:/bin:/usr/sbin:/usr/bin:/usr/bin/X11:/usr/local/sbin:/usr/local/bin

As you can see, the path obtained as a user bloggs included also the directories /usr/games/, /opt/prova/bin/ and ./bin/. When one becomes a root user, one gets additional directories, but other ones, that normally are available, disappear. To solve this problem, it is sufficient to use su with a special option: -.

exit[Enter]

su -[Enter]

Password: ameba[Enter]

whoami[Enter]

root

echo $PATH[Enter]

/sbin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin: (continue)
  /usr/bin/X11:/usr/games:/opt/prova/bin:/bin:./bin

589.2.7   Conclusion

The mechanism used to access the system must be clear before doing anything else. Before continuing, it is important to have understood the examples seen so far, especially because the way to access the system, terminate the work session and change the user identity will not be presented again.

It is important to keep in mind that the computer cannot be switched off before completing the system halt procedure with the shutdown command.

If you have any doubts, please repeat the previous exercises.

589.3   Changing the passwords

The first rule for a safe password consists in its frequent update. When the password is changed, the user is requested to initially enter the previous one, then one can enter a new one, twice, in order to detect typing errors. If the password is too simple, it is not accepted (only the root user has the possibility to assign simple passwords).

589.3.1   Chenges of user passwords made by root

The root user can change the password of another user. This is common situation when new users are created: it is up to the root user to assign the first password to the new user.

passwd bloggs[Enter]

Since the root changes the password of another user, the system requests to just enter the new one (the root user doesn't need to know the old password of another user).

New UNIX password: 123[Enter]

The password that has been entered (which actually is not displayed) is too short and also too simple. The program produces a warning about it, but does not forbid it.

BAD PASSWORD: it's a WAY too short

Retype new UNIX password: 123[Enter]

passwd: all authentication tokens updated successfully

The password has been changed.

589.3.2   Change of the password made by a regular user

The common user can change his/her own password, only that one, but is not allowed to assign a password which is too simple. In our example the user is bloggs.

passwd[Enter]

Before accepting a new password, the old one is requested.

Changing password for bloggs

(current) UNIX password: 123[Enter]

Then the new one is requested.

New UNIX password: tree[Enter]

BAD PASSWORD: it is based on a (reversed) dictionary word
passwd: Authentication token manipulation error

As you can see, the password tree is considered too simple and the program refuses to accept it. The user can then decide to enter a word more complex, or simply longer.

passwd[Enter]

Changing password for bloggs

(current) UNIX password: 123[Enter]

New UNIX password: fra martino campanaro[Enter]

The user has opted for a long password. It is important to remember that the difference between upper and lower case characters is important and that the spaces inserted between words are alse relevant.

Retype new UNIX password: fra martino campanaro[Enter]

passwd: all authentication tokens updated successfully

It is possible that, depending on the system configuration and the libraries version, it is useless to use passwords longer than eight characters, because everything exceeding the eight characters would be simply ignored. You can check that; by trying the proposed example, it might be that the resulting password is only fra mart.

589.3.3   Conclusion

The password changes in a GNU/Linux system, as in any other Unix systems, must be considered something normal, even for regular users. The passwords are not acceptable if they are too simple.

589.4   Directories navigation

The data contained in a file system are organized hierarchycally through directories and subdirectories. Before starting the following exercises, it is useful to review the section 587.7.

The user referred in the examples is bloggs.

589.4.1   Current directory

When the system is used, the commands that are executed are affected by the current position of the user, i.e by the actual or active directory. Technically there is no need to define a current directory: all positions in the tree of the file system can be found explicitely in a precise way. In practice, the existence of this current directory simplifies many things.

cd /usr/bin[Enter]

After entering the previous command, the current directory should become /usr/bin/. This can be checked by entering the following command:

pwd[Enter]

/usr/bin

589.4.2   Absolute and relative paths

The command cd can be used to change the current directory, by either requesting an absolute path or a relative one. The absolute path starts from the root directory, whereas the relative one starts from the current position.

cd /usr/local[Enter]

The command above changes the current directory corrente by moving exactly to /usr/local/. The requested path is absolute because it starts with s slash which represents the la root directory.

pwd[Enter]

/usr/local

When the path does not start with a slash, one refers to something that starts from the current position.

cd bin[Enter]

This command changes the current directory, by moving to bin/ that is a child of the previous current directory.

pwd[Enter]

/usr/local/bin

589.4.3   Moving backwards

Every directory contains two conventional references to two special subdirectories. They are the reference to the same directory where it is contained, represented by a single dot (.), together with a reference to the parent directory, represented by two sequential dots (..). These sysmbols (the single dot and the double dot) can be used as any other directory name.

cd ..[Enter]

It changes the current directory, by moving to the parent directory of the previous one; in other words this directory could be defined as the one that can be found before the starting position. It is a relative path that uses, as its starting point, the current directory from where the command is executed.

pwd[Enter]

/usr/local

The relative backwards movements can be more complex.

cd ../bin[Enter]

In this case the command requests to move back to the previous directory and then move to the directory bin/.

pwd[Enter]

/usr/bin

The backwards movements can also be cumutated at different levels.

cd ../../var/tmp[Enter]

In this case the command requests to move back twice before moving ahead to the specified directory.

pwd[Enter]

/var/tmp

The backwards movements can even be used in stranger ways that may look useless.

cd /usr/bin/../local/bin/..[Enter]

Clearly this does not make much sense, but it is useful to understand the possibilities provided by the reference to the previous directory.

pwd[Enter]

/usr/local

589.4.4   Riferimento preciso alla directory corrente

The current directory corrente may be represented by a single dot at the beginning of the path.(3) Actually, all relative paths could begin with the prefix ./ (dot, slash). This is not very useful to move through directories, but it is useful in other situations.

cd ./bin[Enter]

The command requests to move from the current directory corrente to the directory bin/.

pwd[Enter]

/usr/local/bin

589.4.5   Current directory and ``.''

The current directory has not the same meaning as the reference .: the . ``file'' is a shortcircuit that exist in any directory. For example, the path one/two/./three is completely equivalent to one/two/three. In practice, the dot that exists in first instance, represents a null movement in the same directory directory one/two. This can be easily verified:

cd /usr/./local/./lib[Enter]

pwd[Enter]

/usr/local/lib

When a relative path is used, it is like implicetely using a dot at the beginning of the current directory; therefore, the notation ./one/two, means an equivalent concept as current_directory/./one/two. Therefore, only when the dot is at the beginning of a path (that is consequently relative), it represents the current directory.

589.4.6   Personal directory personale, or home directory

Every user has a personal directory , known as home directory, which should contain everything that is connected to the owning user. By using the command cd without any argument, one reaches the personal directory, without explicit indication.

cd[Enter]

pwd[Enter]

/home/bloggs

Some shell replace the tilde character (~), at the beginning of a path, with the personal directory of the user that has entered the command.

cd ~[Enter]

pwd[Enter]

/home/tizio

In the same way, a user-name preceded by a tilde character, is replaced by the personal directory of the same user.(4)

cd ~brown[Enter]

pwd[Enter]

/home/brown

Before continuing, you should move back to your own personal directory.

cd[Enter]

589.4.7   Conclusione

The current directory is an important reference point for the programs and it can be changed by using the command cd. You can find the current directory by using the command pwd. You can refer to the parent directory of the current one by using two sequential dots (..), whereas you can refer to the the current one (according to the context in which yoy are) with a single dot (.).

589.5   Contents

The navigation of directories can be done in a blind way, as we have seen in the examples of the previous exercise, but this is not usual: normally it is done together with the analysis of the directories and files contents.

589.5.1   Directory contents

The directories can be explored with the command ls

ls /bin[Enter]

arch           dd             gzip           nisdomainname  tar
ash            df             hostname       ping           touch
awk            dmesg          kill           ps             true
basename       dnsdomainname  ln             pwd            umount
bash           doexec         login          rm             uname
bsh            domainname     ls             rmdir          vi
cat            echo           mail           rpm            view
chgrp          egrep          mkdir          sed            vim
chmod          ex             mknod          sh             ypdomainname
chown          false          more           sleep          zcat
cp             fgrep          mount          sort
cpio           gawk           mt             stty
csh            grep           mv             su
date           gunzip         netstat        sync

The command ls /bin shows the content of the directory /bin/. The names that are listed represent file of any type (including subdirectories).

A more complete display of the directory content can be achieved by using the option -l.

ls -l /bin[Enter]

-rwxr-xr-x   1 root     root         2712 Jul 20 03:15 arch
-rwxrwxrwx   1 root     root        56380 Apr 16  1997 ash
lrwxrwxrwx   1 root     root            4 Oct 21 11:15 awk -> gawk
-rwxr-xr-x   1 root     root        18768 Apr 18  1997 basename
-rwxrwxrwx   1 root     root       412516 Jul 17 21:27 bash
lrwxrwxrwx   1 root     root            3 Oct 21 11:15 bsh -> ash
-rwxr-xr-x   1 root     root        22164 Mar 14  1997 cat
-rwxr-xr-x   1 root     root        23644 Feb 25  1997 chgrp
-rwxr-xr-x   1 root     root        23960 Feb 25  1997 chmod
-rwxr-xr-x   1 root     root        23252 Feb 25  1997 chown
-rwxr-xr-x   1 root     root        61600 Feb 25  1997 cp
-rwxr-xr-x   1 root     root       296728 Apr 23  1997 cpio
...

In this instance, we have obtained a more detailed list which especially allows to distinguish the type of file, the permissions and the owner and group users.

We have explained before that each directory contains two conventional references represented by a single point or by two sequential points (. e ..). In the above examples, these do not appear. This happens because the files whose name begin with a dot are not considered unless they are explicitely requested.

cd[Enter]

ls[Enter]

The personal directory of a user might look empty, by using the command ls just presented above. if you use the option -a also the files which befin with a dot are presented (notice that previously the references . e ..) did not appear.

ls -a[Enter]

.                .bash_profile    .riciclaggio
..               .bashrc          .screenrc
.Xdefaults       .fvwm2rc95       .twmrc
.bash_history    .mc.ext          .xfm
.bash_logout     .mc.ini          .xinitrc

589.5.2   File contents

It is possible to analyse also the content of files, with some limits, especially if they are text files. To display the content of text files one can generally use the commands cat and more.

cat /etc/fstab[Enter]

/dev/hda3       /               ext3            defaults        1  1
/dev/hda2       none            swap            sw
proc            /proc           ignore
/dev/hda1       dos             vfat            quiet,umask=000
/dev/hdc        /mnt/cdrom      iso9660         ro,user,noauto
/dev/fd0        /mnt/floppy     vfat            user,noauto,quiet

The command shown above allows to display the content of the file /etc/fstab, which can obviously be different according to the configuration of your system.

cat, used as above, is not suitable to the display of files having a large size. In this case it is better to use the command more, or the more sophysticated less.

more /etc/services[Enter]

# /etc/services:
# $Id: services,v 1.4 1997/05/20 19:41:21 tobias Exp $
#
# Network services, Internet style
#
# Note that it is presently the policy of IANA to assign a single well-known
# port number for both TCP and UDP; hence, most entries here have two entries
# even if the protocol doesn't support UDP operations.
# Updated from RFC 1700, ``Assigned Numbers'' (October 1994).  Not all ports
# are included, only the more common ones.

tcpmux          1/tcp                           # TCP port service multiplexer
echo            7/tcp
echo            7/udp
discard         9/tcp           sink null
discard         9/udp           sink null
systat          11/tcp          users
daytime         13/tcp
daytime         13/udp
netstat         15/tcp
qotd            17/tcp          quote
msp             18/tcp                          # message send protocol
msp             18/udp                          # message send protocol
--More--(5%)

[space bar]

chargen         19/tcp          ttytst source
chargen         19/udp          ttytst source
ftp-data        20/tcp
ftp             21/tcp
fsp             21/udp          fspd
ssh             22/tcp                          # SSH Remote Login Protocol
ssh             22/udp                          # SSH Remote Login Protocol
telnet          23/tcp
# 24 - private
smtp            25/tcp          mail
# 26 - unassigned
time            37/tcp          timserver
time            37/udp          timserver
rlp             39/udp          resource        # resource location
nameserver      42/tcp          name            # IEN 116
whois           43/tcp          nicname
re-mail-ck      50/tcp                          # Remote Mail Checking Protocol
re-mail-ck      50/udp                          # Remote Mail Checking Protocol
domain          53/tcp          nameserver      # name-domain server
domain          53/udp          nameserver
mtp             57/tcp                          # deprecated
bootps          67/tcp                          # BOOTP server
bootps          67/udp
--More--(9%)

As shown, to move to next screen, you can just press the [space bar]. To exit, even if the file has not been viewed completely, you can just enter the letter ``q''.

[q]

less works in a similar way, but allows also to view the file backwards, by using keyboard keys in an intuitive way.

more and less are better described in the section ##en-doc-readme##.

589.5.3   Type determination

The file content can be determined also by using the command file, without displaying its content. This is very important, especially when the display of the file content is not a suitable option (think at the result of displaying the content of an executable binary file).

The command file is based on a series of reconnaisance strings called magic number (a kind of ``stamp''), defined according to the tradition of the Unix systems.

file /etc/*[Enter]

/etc/DIR_COLORS:       English text
/etc/HOSTNAME:         ASCII text
/etc/X11:              directory
/etc/adjtime:          ASCII text
/etc/aliases:          English text
/etc/aliases.db:       Berkeley DB Hash file (Version 2, Little Endian,...
/etc/at.deny:          ASCII text
/etc/bashrc:           ASCII text
/etc/cron.daily:       directory
/etc/cron.hourly:      directory
/etc/cron.monthly:     directory
/etc/cron.weekly:      directory
/etc/crontab:          ASCII text
/etc/csh.cshrc:        ASCII text
/etc/dosemu.conf:      English text
/etc/dosemu.users:     ASCII text
...

The command of the example abone displays the list of the files contained in the directory /etc/, together with the definition of the file type.

This method is not infallible, but is anyway a great help.

589.5.4   Used space and available space

The command df allows to check the available space on the disk (or disks).

df[Enter]

The results is something similar to the following.

Filesystem         1024-blocks  Used Available Capacity Mounted on
/dev/hda4             648331  521981    92860     85%   /
/dev/hda1              41024   38712     2312     94%   /dos

The command du can be used to find the used space in a directory.

du /bin[Enter]

3168    /bin

In the example above, one can see that the directory /bin/ contains files that use a total of 3 168 Kbytes.

589.5.5   Conclusion

The analysis of the directory or file contents is an elementary operation, but is very important to determine the actions to be taken according to the results of the investigations.

589.6   Creation, copy and removal of files

The creation, the copy and the removal of files are elementary operations, but they are important and delicate. This exercise should be done with focus and attention.

589.6.1   File creation

There are many ways to create a file. The simpler way to create an empty file consists in using the command touch. First of all, one should move to the personal directory, which is the better place to do this kind of exercises.

cd[Enter]

touch pippo[Enter]

After using the command touch to create the file pippo no confirmation of the creation is returned by the system. This is a typical behaviour of the Unix systems whose commands normally do not show the success of the performed operations. It is however easy to check.

ls -l pippo[Enter]

-rw-rw-r--   1 bloggs   bloggs          0 Dec 23 10:49 pippo

The file has been created.

In this phase of the exercises, when no description has yet been given about the usage of a program to create or edit a text file, we can see a simple method to create such a file. We can use the command cat in a strange way that will be clarified later on.

cat > pippo2[Enter]

We can then start to enter text as shown below.

There is also a simple way to write[Enter]

a text file.[Enter]

Unfortunately it is a one way only writing.[Enter]

[Ctrl+d]

The text entry terminated by using the combination [Ctrl+d].

You can check that the file has been created and contains the entered text.

cat pippo2[Enter]

There is also a simple way to write
a text file.
Unfortunately it is a one way only writing.

589.6.2   Copying files

Files can be copied by using the command cp.

cp pippo2 pippo3[Enter]

By executing the command above, one gets the copy of the file pippo2 into the file pippo3. As in the other cases, if everything is successful no further message is produced.

It is possible to copy a group pf files only if the destination (the last name of the command line) is a directory that exists already.

cp pippo pippo2 pippo3 /tmp[Enter]

The previous command copies the files created until now into the directory /tmp/. The same result can be achieved in a simpler way by using wildcard characters.

cp pippo* /tmp[Enter]

589.6.3   Removing files

Files can normally be deleted (removed) by using the command rm. This command must be used with plenty of attention, especially if one works with the privileges of the root user. Actually, the removal is done without any objection and without asking for confirmation. One simple error can cause the deletion of everything that the user is authorised to access.

rm pippo pippo2[Enter]

The command presented above deletes the files pippo e pippo2 finally and without any possibility to recover the listed files.

The file deletion can also be done by using wildcard characters. The use of these symbols represents an additional risk. Generally, when one has not yet a good preparation and might be uncertain about the effects of a removal command, it would be advisable to check the results before, for instance by using ls.(5)

If one wants to delete all file whose name begins with pippo, one could use the model pippo*. For security one should check with ls.

ls pippo*[Enter]

pippo3

Only the file pippo3 matches the model. Actually, the files pippo and pippo2 have just been reoved. Anyway, we see that the model is correct and we can continue with the deletion (by still paying a lot of attention).

rm pippo*[Enter]

Some lack of attention in using this command, can cause serious consequences. Just think about what can happen if, instead of typing rm pippo* one accidentally enters a blank between the work pippo and the asterisk. The command would become rm pippo * and would produce the removal of the file pippo (if it exists) and later the removal of all files in the current directory (this is what a single asterisk represents). As already explained, rm does not asks for confirmation, as most of the other commands, according to the Unix tradition: whatever is deleted, it is deleted.

589.6.4   Conclusion

The creation of files, normally empty, the copy and removal are elementary but fundamental operations. In their simplicity they still have functionality that requires some attention, especially when one has the privileges of the root user: the copy can cause the overwriting of existing files, the deletion could happen in an environment which is different from the planned or wished one.

589.7   Creation, copy and removal of a directory

The directories can be seen as containers of files and other directories. The copy and removal of directories has different implications than the same operations done on regular file. The recommandation to do the exercise with attention is still valid.

589.7.1   Creating a directory

The creation of a directory is conceptually similar to the creation of an empty file. When a directory is created is always empty: files will be added when it is used. A directory is created by the command mkdir.

Before starting, you should move to your perdonal directory and then create the directory mine/ whose parent will be the current position.

cd[Enter]

mkdir mine[Enter]

You can check the result with the command ls.

ls -l[Enter]

...
drwxr-xr-x   8 bloggs   bloggs       1024 Dec 23 12:11 mine
...

The letter d at the beginning of the permissions string identifies it clearly as a directory.

589.7.2   Copying a directory

A directory can be copied by using the command cp with the options -r or -R, having a small difference that we do not discuss yet.

cp -r mine mine2[Enter]

The command above produces a copy of the directory mine/ into mine2/. The copy is recoursive, i.e. it includes all files of the original directory, together with all possible sottodirectories, including their content.

589.7.3   Removing a directory

Normally a directory can be removed only when it is empty, by using the command rmdir.

The same prudence recommandations previously made for the exercises on the deletion of files are still valid..

rmdir mine2[Enter]

The command above removes the directory mine2/.

The removal of a directory done in this way, i.e. by using the command rmdir, is not worrying, because the command allows to delete only empty directories: if one removes one directory by error, one can easily re-create it by using the command mkdir.

However, often full branches of a directory are removed, when a single command is used to remove one or more directories and their content. This approach is referred to as a recoursive deletion.

Before continuing, we create a multi-level directory structure.

mkdir carbon[Enter]

mkdir carbon/hydrogen[Enter]

mkdir carbon/hoxigen[Enter]

mkdir carbon/hydrogen/helium[Enter]

One should obtain a structure organized as follows:

tree carbon[Enter]

carbon
|-- hydrogen
|   `-- helium
`-- hoxigen

3 directories, 0 files

If you try to remove all the structure that starts from carbon/ by using the command rmdir, you will get only an error message.

rmdir carbon[Enter]

rmdir: carbon: Directory not empty

For this reason, it is necessary to use the command rm with the option -r. However the command rm used in this recoursive mode is especially dangerous if one does not pay attention.

rm -r carbon[Enter]

The directory carbon/ and all the child directories have been removed.

Think about what might happen if wildcard characters are used: all files and directories that match the pattern are removed. There is still something worse: the danger of the names that start with a dot.

589.7.4   Removing directories whose name start with a dot

The deletion of a directory whose name starts with a dot is an extremely delicate operation that requires a separate discussion. Generally, when wildcard chracters are used to identify a group of file or directory names, the symbols never match names that start with a dot. This convention has been defined to avoid that wildcard characters interfere with the starndard directory references: . (the same directory) and .. (the previous directory).

There is also the additional convention to use an initial dot for files and directories that represent the special configuration of each user. By using this convention, those files and directory appear to be hidden and the user is not bothered by them, which therefore cannot be involuntary removed.

One might wish to remove all those files and directories, by using the pattern .* (dot, asterisk), but this would remove also the standard references: . and .., thus removing also the current and the parent directory.

Moreover, if this is done in a recoursive way, by using the option -r, you would request to delete the full file system.

If the command is entered by a normal user, it will remove only the data that can be accessed by the user, but if this error is done by the root user, it will be a complete disaster.

In conclusion the dangerous command is rm -r .*. Pay attention!

589.7.5   Conclusion

When one copies or removes directories, it is normal to wish to do it recoursively on all the content of the starting directory. The main problems exist with the recoursive removal, especially when one wants to remove files a directories starting with a dot by using a pattern of wildcard characters.

589.8   Moving and Linking files and directories

In the Unix environments, tmoving and changing the name of files and directories are the same action. Another characteristic of the Unix operating systems is the possibility to manage links to files and directories.

589.8.1   Moving and renaming

Files and Directories can be moved by using the command mv. To do some exercises with this command we must prepare some files and some directories.

touch alfa[Enter]

touch beta[Enter]

mkdir gamma[Enter]

Come sempre è bene controllare.

ls -l[Enter]

...
-rw-rw-r--   1 bloggs   bloggs          0 Dec 25 12:46 alfa
-rw-rw-r--   1 bloggs   bloggs          0 Dec 25 12:46 beta
drwxrwxr-x   2 bloggs   bloggs       1024 Dec 25 12:46 gamma
...

We start renaming the file alfa to change it into omega.

mv alfa omega[Enter]

ls -l[Enter]

...
-rw-rw-r--   1 bloggs   bloggs          0 Dec 25 12:46 omega
...

If one wants to move multiple files and directories as a group, it is mandatory that the destination is a directory. By using the following command the two files created before are moved into the directory gamma/.

mv omega beta gamma[Enter]

ls -l gamma[Enter]

-rw-rw-r--   1 bloggs   bloggs          0 Dec 25 12:46 beta
-rw-rw-r--   1 bloggs   bloggs          0 Dec 25 12:46 omega

Generally, there is no difference between moving (or changing the name of) regular files or directories.

mv gamma /tmp[Enter]

The previous command moves the directory gamma/ into /tmp/.

It is important to remember that the command mv cannot change multiple names as a group. For instance, one cannot change *.mine in *.thine.

589.8.2   Links

The creation of a link is an operation which is similar to the copy, with the difference that instead of creating a duplicate file or directory one creates a reference to the original file or directory. There are two types of link: symbolic link and physical link (usually known as hard link). In this exercise only the symbolic links are used.

The command used to create these links is ln;, since only the symbolic ones are used, we will always use the option -s.

Before amking the exercises with this command, we need to prepare some files and directories.

touch uno[Enter]

touch due[Enter]

mkdir tre[Enter]

A usually, it is better to verify.

ls -l[Enter]

...
-rw-rw-r--   1 bloggs   bloggs          0 Dec 25 12:46 due
drwxrwxr-x   2 bloggs   bloggs       1024 Dec 25 12:46 tre
-rw-rw-r--   1 bloggs   bloggs          0 Dec 25 12:46 uno

As suggested before, the creation of a link is an operation which is similar to the copy.

ln -s uno uno.bis[Enter]

By using the command above, one gets a symbolic link, called uno.bis, which refers to the file uno.

ls -l[Enter]

...
lrwxrwxrwx   1 bloggs   bloggs          3 Dec 25 12:47 uno.bis -> uno

From now on, one can refer to the file uno by using the name uno.bis.

The creation of a link to a directory can be done in the same way as that presented for the files (provided that it is a symbolic link).

ln -s /tmp mytemp[Enter]

If the command above has succeeded, one can refer to the directory /tmp/ also by using the reference mytemp.

The creation of a group of links by using a single command, can be done only if the destination (the last name of the command line) is a directory. In this case one gets many links created within the destination directory.

ln -s /home/bloggs/uno* /home/bloggs/due tre[Enter]

In the above case, links are created for all files whose names begin with uno and also for the file due within the directory tre/.

In the above example, the files for which we want to create the symbolic links have been written with their absolute path, even if we assume that the directory /home/bloggs/ was the current one. With this assumption the target directory has been written simply by using the relative path. When multiple links are created in a directory, as we have done above, it is necessary to specify also the path of the files (or directories) used as origin.

ls -l tre[Enter]

lrwxrwxrwx   1 bloggs   bloggs   15 Dec 25 15:21 due -> /home/tizio/due
lrwxrwxrwx   1 bloggs   bloggs   15 Dec 25 15:21 uno -> /home/tizio/uno
lrwxrwxrwx   1 bloggs   bloggs   19 Dec 25 15:21 uno.bis -> /home/tizio/uno.bis

Notice that one of the created links is based on another link.

589.8.3   Conclusion

The move of files or directories works in a similar way as the copy, but the origin is removed. The move of directories to different devices is not possible. An error made with the move can be damaging: if one does not pay enough attention, one can overwrite something that has the same name of the destination file or directory. This is the same problem that can happen with the copy.

The links to files and directories allow to define alternative paths to them.

589.9   The shell

The shell is the tool that allows to interact with the system. The way used to enter command can be very different among from one shell to another. The exercises proposed in this section are based especially on the Bash shell, but many of them can be applicable also to other shells.

589.9.1   Automatic completion

The automatic completion is the approach used by the shell to help a user to coplete a command. The completion request is made by using the [Tab] key. We prepare some examples files. Their names have been chosen to be long.

touch microswitch[Enter]

touch microscopic[Enter]

touch supersonic[Enter]

If we assume that we are going to use these names in a command line, we can be a bit bothered by their length. The problem can be easily solved by using the automatic completion.

ls sup[Tab]

After having written just sup, by pressing the [Tab] key, one caused the completion of the name, since no other files or directories (from the current position) begin in the same way. The following example shows the same command completed and terminated.

ls sup[Tab]ersonic[Enter]

The automatic completion of names might be impossible. Actually, no name might exist to match the initial part already entered, or there might be multiple names having the same prefix. In the latter case, the completion stops at the point when the names become distinct.

ls mic[Tab]ro

In this case, the completion stops with micro which is the common part of the names microswitch and microscopic. To continue it is necessary to add an hint that could allow to distinguish between the two names. If one wants to select the first of those name, one could just enter the letter i and press again the [Tab] key. The following example shows the full procedure.

ls mic[Tab]roi[Tab]nterruttore[Enter]

589.9.2   Substitution: wildcard characters

An alternative way to complete names is represented by the wildcard characters. It is actually up to the shell to transform the symbols used for this purpose.

We will use for the following exercise the files created in the previous section: microswitch, microscopic e supersonic. Later on some new ones will be added when this is requested by the exercise.

589.9.2.1   Asterisc

The asterisc represents an undifined sequence of zero or more characters of any type, except the slash that is used to separate directories. For this reason, an esterisk without other characters represents all file names available in the current directory.

ls[Enter]

The command ls shown above is used to list the names of all the files and directories contained in the current directory.

ls *[Enter]

This command is slightly different, because the shell substitutes the asterisc with the complete list of the file and directory names contained in the current directory. It is as if the command had been ls microswitch microscopic...

In this way, also the behaviour of ls changes: not only it lists the content of the current directory, but (eventually, if they exist) also that of all directories contained in the current one.

The asterisk can be used also together with fixed text parts.

ls micro*[Enter]

The command is processed by the shell by substituting micro* with all the names that begin with micro.

microinterruttore microscopico

We have explained that the esterisk can be replaced also by a null string. To check this we create another file.

touch nanomicro[Enter]

The following command is used to list all the names that contain the word micro.

ls *micro*[Enter]

microswitch microscopic nanomicro

589.9.2.2   Question mark

The question mark represents a single character of any type.

Before continuing we add some new files with names suitable for the following exercises.

touch xy123j4[Enter]

touch xy456j5[Enter]

touch xy789j111[Enter]

touch xy78j67[Enter]

The following command is used to process all files that have a name exactly seven characters lonf and that contain the letter j in the sixth position.

ls ?????j?[Enter]

xy123j4 xy456j5

The result would have been different if we had used an asterisc: it wouldn't been possible to limit the result to the files with a letter j in the sixth position, morever we wouln't have been able to process only the files that are seven characters long.

ls *j*[Enter]

The command above produces the list of all the file names which contain the letter j, without other constraints.

xy123j4 xy456j5 xy789j111 xy78j67

589.9.2.3   Square parentheses

The square parentheses are used to process only the specified characters or a range of characters. They represent a single character about one of those that they contain, or those in the provided range.

ls xy????[4567]*[Entry]

xy123j4 xy456j5 xy78j67

The command presented above has been written to send to ls, as an argument, the list of all the files whose name begin with xy, are followed by four characters of any type, then contain a character in the range 4 to 7 and terminate in any way. The same result could have been achieved by specifying the range within the square parentheses.

ls xy????[4-7]*[Enter]

589.9.2.4   Escape

The fact that the shell replaces some characters actually prevents theis use in the file or directory names. If there is a need to use them, it is possible to avoid the replacement by preceding them with a back slash, that is interpreted as an escape (i.e. as a protection symbol).

touch sei\*otto[Enter]

ls[Enter]

...
sei*otto

In the same way it is possible to include also a space in the file name.

touch sei\ bella[Enter]

ls[Enter]

...
sei bella
sei*otto

It should be mentioned that there are other ways to prevent the shell from interpreting symbols used in the command line, but these are examined in the chapters dedicated to the shell.

589.9.2.5   Checking

The use of wildcard characters can be dangerous when one has not a sufficient experience to determine the exact effect of a command. This is especially true if the command is used to delete. The best way to check the effect of character replacement by wildcard characters is using the command echo, that simply provides to display the list of its arguments.

For instance, in order to know which files and directories are considered by using the pattern micro*, you can use the following command:

echo micro*[Enter]

microswitch microscopic

As an alternative you might use the ls command, which is not destructive, to determine the extension of a wildcard characters pattern. However ls shows also the content of directories entered in the arguments and it might therefore partially distract the user.

589.9.3   Redirection and pipeline

The shell allows to redirect the output of a command which normally would be directed to the display, or the input of a command that normally would be received from the keyboard.

589.9.4   Redirection

The redirection sends the data to a file or receives them from a file.

ls -l > list[Enter]

The command produces the file list as the result of the execution of the command di ls. You can check the content of this file by cat.

cat list[Enter]

It is possible to redirect also the input, when the command can receive it. cat can output whatever is received from the standard input.

cat < list[Enter]

This produces the display of the content of the file list, exectly as before, when the name was enetered as an argument to cat. However now it is received from the standard input through the activity of the shell.

The redirection of the output, as presented until now, produces each time a new file, possibly by overwriting what already exists with the same name. Under this point of view, the redirection of the output might produce damages.

It is also possible to use redirection in addition, by creating a file if it does not exist, or by just adding the data if the file exists already.

ls -l /tmp >> list[Enter]

The command above adds to the file elenco the detailed content list of the directory /tmp/.

cat elenco[Enter]

589.9.5   Pipeline

The pipeline is a type of redirection used by the shell to direct the output of a command to the input of the following one.

cat list | sort[Enter]

The command above causes cat to read the content of the file list, but instead of showing it on the screen, the output is sent by the shell to the standard input of sort that reorders it and then displays it on the screen.

A pipeline can also use the redirection and therefore the previous command can be transfromed as follows,

cat < list | sort[Enter]

or it might be simplified as follows, but in this case it is no more a pipeline.

sort < list[Enter]

589.9.6   Alias

The creation of an alias is a method that allows to define an alternative name for an existing command.

alias list='ls -l'[Enter]

After defining the alias list as above, you can use it to produce the same results as di ls -l. Just try.

list[Enter]

The alias allows also to use arguments, as if it were a normal command.

list micro*[Enter]

The result is the same as that produced by the command ls -l micro*.

-rw-rw-r--   1 bloggs   bloggs          0 Dec 26 10:19 microswitch
-rw-rw-r--   1 bloggs   bloggs          0 Dec 26 10:19 microscopic

Typical aliases as follows are cretated to request a confirmation before operations of deletion or overwriting.

alias rm='rm -i'[Enter]

alias cp='cp -i'[Enter]

alias mv='mv -i'[Enter]

You can try to remove a file to check what happens.

rm microswitch[Enter]

rm: remove `microswitch'?:

n[Enter]

According to the reply, the file has not been removed.

An alias can be simply removed by using the intuitive command unalias:

unalias list[Enter]

The command above removes the alias elenca in a selective way, whereas the command below removes all the aliases that still exist:

unalias -a[Enter]

By doing this, at the end of the shell working session, the aliases are lost.

589.9.7   Conclusion

The completion of names and the use of wildcard are the most important tools provided by the shell. However, the use of patterns with wildcard characters can cause serious errors, therefore, before using destructive commands, it is advisable to check the effect of thse patterns by using echo.

The redirection and the pipeline are very important tools which allow to build very complex commands by combining elementary commands.

589.10   Process control

When one uses a multiprogramming environment, it is important to control the active processes. A process is a single executable in action, but a command can generate multiple processes.

589.10.1   Displaying the process status

The main command for process control is ps.

ps[Enter]

  PID TTY STAT  TIME COMMAND
  077   1 SW   0:01 (login)
  078   2 SW   0:01 (login)
  091   1 S    0:01 -bash
  132   2 S    0:01 -bash
  270   1 R    0:00 ps 

In the case above ps shows that there are two active copies of bash (the Bash shell), and that each of them is connected to a different terminal (the first and second virtual console), tty1 e tty2. The only working program is the same ps, that in this example has been started from the first terminal

By using the option f, you can see the dependences beween processes.

ps f[Enter]

  PID TTY STAT  TIME COMMAND
  077   1 SW   0:01 (login)
  091   1 S    0:01  \_ -bash
  275   1 R    0:00      \_ ps -f
  078   2 SW   0:01 (login)
  132   2 S    0:01  \_ -bash

A better graphical presentation is produced by pstree.

pstree[Enter]

init-+-crond
     |-kflushd
     |-klogd
     |-kswapd
     |-login---bash
     |-login---bash---pstree
     |-4*[mingetty]
     |-4*[nfsiod]
     |-portmap
     |-rpc.mountd
     |-rpc.nfsd
     |-syslogd
     `-update

Whereas before one could see only processes connected to terminals, now the command shows all active processes. The list changes according to the system configuration.

589.10.2   Process Removal

The processes are removed automatically when they terminate regularly. Sometimes a forced termination might become necessary.

To try this, you can move to the second virtual console and start from there a useless program that can then be removed from the first console.

[Alt+F2]

If necessery access the system and enter the following.

yes[Enter]

y
y
y
y
...

By using yes one obtains the continuous production of the letter ``y''. You can move to the first console and observe the situation.

[Alt+F1]

ps[Enter]

  PID TTY STAT  TIME COMMAND
  077   1 SW   0:01 (login)
  078   2 SW   0:01 (login)
  091   1 S    0:01 -bash
  132   2 S    0:01 -bash
  311   2 R    0:26 yes 

We decide to remove the process generated by yes by sending a termination signal.

kill 311[Enter]

The number 311 has been associated to the process, or PID, that is obtained by observing the output of the command ps. If you go back to the console from which the yes had been executed, you find that this has terminated its execution.

[Alt+F2]

...
y
y
Terminated

589.10.3   Background processes

The shell allows to start commands in the background thus allowing the immediate display of the prompt to enter other commands.

yes > /dev/null &[Enter]

This command starts yes by redirecting the output to the file /dev/null which is a special device comparable to a rubbish bin without limits (whatever is sent there is eliminated). The symbol ampersand (&), entered at the end of the command, causes the shell to execute it in the background.

Of course, it makes sense to execute a command in the background when this does not requests input from the keyboard and does not produce output to the display.

589.10.4   Conclusion

The process control is based mainly on the commands ps and kill. The shell allows normally some form of contral on the commands started from there; they are usually known as shell job.

The chapter ##en-capitolo-processi## and the following ones describe this subject in a more detailed way.

589.11   Permissions

The permissions define the privileges on files or directories of the owning user, of the group and of the other users.

The section 587.7.5 introduced the problems connected to the permissions, and especially the way in which they can be represented in a numeric form.

589.11.1   File permissions

There three different types of file permissions: read, write and execute. Whereas execute permission (it refers to the executable files and the scripts) and the read permission are sufficiently logical, the write permission might make one think that it is meant to be used to avoid the deletion. It's not like that, the possibility to delete a file depends instead on the directory's permissions.

touch my_file[Enter]

chmod -r my_file[Enter]

By doing this the read permission has been removed for all users, including the owner.

ls -l my_file[Enter]

--w--w----   1 bloggs   bloggs          0 Dec 26 10:24 my_file

Notice that the letter r has been removed from the permissions string.

cat my_file[Enter]

cat: my_file: Permission denied

The content of the file cannot be displayed because the read permission is missimg (in this case the file is actually empty and there is nothing to be displayed, but the result shows that the system does not allow any reading operation).

chmod +r my_file[Enter]

Before checking what happens after the removal of the write permission, the command above is used to add again the read permission.

chmod -w my_file[Enter]

The command above removes the write permission; this prevents any change of the file, but does not prevent its deletion.

ls > my_file[Enter]

bash: my_file: Permission denied

The above attempt to overwrite causes an error message, as you can see above, and the same thing would happen with any attempt to change the content of the file.

mv my_file your_file[Enter]

The move or name change is possible.

ls -l your_file[Enter]

-r--r--r--   1 bloggs   bloggs          0 Dec 26 10:24 your_file

The deletion is also acceptable; probably you would get a warning, but nothing more.

rm your_file[Enter]

rm: remove `your_file', overriding mode 0444? 

y[Enter]

The file, finally, is deleted.

589.11.2   Directory permissions

Also on the directories it is possible to set three permission types: read, write and execute. If you don't know the Unix operating system, the meaning might not be intuitive.

mkdir testdir[Enter]

touch testdir/one[Enter]

touch testdir/two[Enter]

By removing the read permission, the content of the directory cannot be listed, i.e. it is not possible to use commands such as ls, whereas it is still possible to access the files (provided that their name is known).

chmod -r testdir[Enter]

ls testdir[Enter]

ls: testdir: Permission denied

Before continuing the read permissions are restored.

chmod +r testdir[Enter]

The write permissions allow to add, remove and rename the files (including the possible subdirectories).

chmod -w testdir[Enter]

The command above removes the write permission of the directory testdir/.

rm testdir/one[Enter]

rm: testdir/one: Permission denied

cp testdir/one testdir/three[Enter]

cp: cannot create regular file `testdir/three': Permission denied

mv testdir/one testdir/three[Enter]

mv: cannot move `testdir/one' to `testdir/three': Permission denied

Before continuing the write permission is restored.

chmod +w testdir[Enter]

The execute permission is the strangest one. It prevents the access to the directory and all its content. This means that it prevents the access to all its files and to the child directories.

We create a child directory of testdir/.

mkdir provedir/tmp[Enter]

Si crea un file al suo interno, per poter verificare in seguito quanto affermato.

touch provedir/tmp/esempio[Enter]

Si tolgono i permessi di esecuzione a provedir/ per vedere cosa accade.

chmod -x provedir[Enter]

Da questo momento, provedir/ e tutto quello che ne discende è inaccessibile.

cd provedir[Enter]

bash: cd: provedir: Permission denied

cat provedir/tmp/esempio[Enter]

cat: provedir/tmp/esempio: Permission denied

touch provedir/tmp/esempio2[Enter]

touch: provedir/tmp/esempio2: Permission denied

589.11.3   Permissions Mask: umask

The permissions mask, i.e. the mask umask, determines the permissions that must be removed when a file or a directory is created without an explicit specification of its permissions. In the same way, when permissions are entered without defining at which level they refer (to the user, the group or the other, as it was done in the previous sections), the permissions in the permissions mask are removed. In order to find the value of this mask, it is sufficient to enter the following command:

umask[Enter]

002

If the system is configured as it was suggested at the beginning of the chapter, this is the value above is returned. Often the value of the permissions mask is 0228.

The number two represents a write permission, in this instance referred to the other users. This means that the permission is removed in a predefined way. If the value had been 0228, the write permission would have been removed also from the group.

A more explicit representation of the permissions mask can be obtained by using the option -S.

umask -S[Enter]

u=rwx,g=rwx,o=rx

In this way one obtains the representation of the permissions that are assigned in a predifined way.

Let's suppose, as an exercise, that we are in a situation where we want to prevent any other users from accessing our data (except the user root that cannot be prevented from anything).

umask 077[Enter]

The number seven represents all permissions (read, write and execute) and these are systematically removed from the group and the other users. You can test this by creating a file.

touch secret[Enter]

ls -l secret[Enter]

-rw-------   1 bloggs   bloggs          0 Dec 27 11:10 secret

touch has not tried to assign any execute permission, therefore this does not appear in the list of the user permissions.

mkdir secret[Enter]

ls -l[Enter]

...
drwx------   2 bloggs   bloggs       1024 Dec 27 11:14 secret
...

As you can see in the example, also the creation of a directory is affected by the permissions mask.

589.11.4   Conclusion

The meaning of the permissions on files and directories is not necessaraly intuitive or evident. Some training is needed to understand their meaning.

The permissions mask, or umask, is a tool to filter the unwished permissions in normal operatiosn, when they are not explicitely assigned.

589.12   Text creation and changes

All Unix courses demonstate the use of a rather spartan application, for text file creation and changes: VI. Actually this is based on the executable program vi. The need to learn how to use this program, at least in a basic way, depends on the fact that it uses limited memory resources and often is included in the set of service programs that compose the emergency diskettes.

589.12.1   Command and entry modes

The use of VI is difficult because it works in different modes. In practice the text entry phase is separated from the command one.

To enter a command, one must suspend the text entry by pressing the [Esc] key. To change again to the text entry mode a corresponding command must be entered.

The [Esc] key can also be used to cancel a command that has not been completed yet. If it is pressed more than the necessary time, it has not any collateral effect.

589.12.2   Creation, insertion and modification

A new file is created by simply starting the program without any arguments.

vi[Enter]

As soon as it starts, VI uses the full screen.

_
~
~
~
~
~
Empty buffer

The tilde (~) symbols represent null (non existing) rows.

At this moment the program is in command mode and accepts command expressed by letters or keyboard symbols.

589.12.2.1   Text entry

By pressing the [i] key, which represents the insertion command (insert), one switches to the insert mode that allows to enter normal texts.

[i]

GNU/Linux is a complete operating system[Enter]

whose kernel has been written by[Enter]

Linus Torvalds and other partners.

The screen should now present the following and the cursor should be positioned at the end of the last entered text.

GNU/Linux is a complete operating system
whose kernel has been written by
Linus Torvalds and other partners._
~
~
~
-- INSERT --

The insert mode is terminated by pressing the [Esc] key and the command mode is restarted.

[Esc]

589.12.2.2   Cursor movements

In command mode, the cursor can be moved through the text by pressing the [h], [j], [k] and [l] keys which correspond in the same order to the left, down, up and right movements. In most situations it is also possible to use the arrow keys, also during the entry phase.

Let's decide to move the cursor before the word ``operating'' in the first line.

[h][h][h][h][h][h][h][h][h]

[k][k]

In practice we move the cursor nine positions to the left and three upwards.

GNU/Linux is a complete_operating system
whose kernel has been written by
Linus Torvalds and other partners.
~
~
~

589.12.2.3   Deletion

In command mode, texts can be deleted by using the [x] key. It causes the deletion of the character at the cursor position and the shifting of the remaining text.

In most cases it is also possible to use the [Delete] key with the same result. It should work both in command and entry mode.

We decide to delete the word ``operating''.

[x][x][x][x][x][x][x][x][x]

GNU/Linux is a complete_system
whose kernel has been written by
Linus Torvalds and other partners.

A full line can be deleted by entering the command dd i.e by pressing the [d] key twice in sequence.

We decide to delete the last row. First we move the cursor on that line by pressing the [j] key twice, then we continue with the deletion.

[j][j]

[d][d]

GNU/Linux is a complete_system
whose kernel has been written by
~
~
~
~

589.12.3   Saving and terminating

The text can be saved to an output file by using a command that is more complex than those presented so far. In command mode, one must press the [:] key which starts a special command, called colon or last row, because it appears in the last screen row.

[:]

GNU/Linux is a complete_system
whose kernel has been written by
~
~
~
~
:_

The command to save is

:w file_nome

and we decide to save with the name mytext.

w mytext

The screen should now appear as follows.

GNU/Linux is a complete_system
whose kernel has been written by
~
~
~
~
:w mytext_

The command is completed by pressing the [Enter] key.

[Enter]

The termination of VI is obtained by entering the command :q. If one wants to terminate without saving, one should add to the command an exclamation mark (:q!).

:q[Enter]

589.12.4   Opening an existing file

If you want to start the vi program in order to open immediately an existing file and change it, you can just enter the name of the file on the command line.

vi mytext[Enter]

GNU/Linux is a complete_system
whose kernel has been written by
~
~
~
~
``miotesto'' 1 line, 66 characters

As an alternative, you can enter the vi command :e with the following syntax:

:e file_name

The result is the same.

589.12.5   Conclusion

VI is an application for the creation and modification of text files, it is not very sophysticated and it is rather complex to use. However it is necessary to know how to use it in the situations where no better program is available, or where they cannot be used because of system space limitations.

The exercise on VI is just an introduction to the functions of this program, which, even if it might not look so, offers many possibilities and options that in the long run can be found to be really useful. The chapter ##en-capitolo-editing## presents a bit better the possibilities offered by this and other similar programs.

589.13   Executable files

The regular files that have execute permissions, are considered by the operating system as programs that can be run. Of course, this can actually happen only if the operating system can execute their content.

589.13.1   Program start and PATH variable

The request of a program execution requires generally the indication of a relative or absolute path:

/bin/uname -a[Enter]

Linux dinkel 2.2.15 #1 Thu Aug 31 15:55:32 CEST 2000 i586 unknown

However often one does not know where the executable program can be found, but usually it is still possible to start it by leaving up to the system the automatic search of its location:

uname -a[Enter]

Linux dinkel 2.2.15 #1 Thu Aug 31 15:55:32 CEST 2000 i586 unknown

This automatic search depends on the configuration of the PATH environment variable, which is used to list all paths needed to access the executable programs:

echo $PATH[Enter]

/usr/local/bin:/usr/bin:/bin:/usr/bin/X11

The listed paths, separated by colons, represent the directories that are searched to find the executable files when their path has not been explicitely specified (the list in your system might be much longer than our example).

Generally, the current directory, represented by a single dot ., is not included in the path. This can be checked by copying a known program into your personal directory.

cd[Enter]

cp /bin/uname ./my_uname[Enter]

At this point the program uname has been copied into the personal directory with the local name my_uname. You can check whether it is still working properly:

./my_uname -a[Enter]

Linux dinkel 2.2.15 #1 Thu Aug 31 15:55:32 CEST 2000 i586 unknown

However the program cannot be started without specifying its path:

my_uname -a[Enter]

bash: mio_uname: command not found

There is a good reason to avoid starting automatically programs from the current directory; however this possibility could be easily added by changing the content of the PATH variable:

export PATH="$PATH:."[Enter]

echo $PATH[Enter]

/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:.

Now the program my_uname can be started automatically without specifying its path:

my_uname -a[Enter]

Linux dinkel 2.2.15 #1 Thu Aug 31 15:55:32 CEST 2000 i586 unknown

In the list of paths written in the PATH environment variable, there might be multiple programs with the same name. You can check which of them is started first according to the path, you can use the command which:

which uname[Enter]

/bin/uname

which mio_uname[Enter]

./mio_uname

You can change the name of your local copy of the program to use the original name,

mv my_uname uname[Enter]

You can then check which one is actually started, when the path is not included:

which uname[Enter]

/bin/uname

You can change the order of paths in the PATH environment variable, to obtain a different result:(6)

export PATH=".:$PATH"[Enter]

echo $PATH[Enter]

.:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:.

which uname[Enter]

./uname

589.13.2   Internal shell commands

What is started is not always an executable program; it could be an internal shell command. For example, if you use the Bash shell, you can use the command help to obtain their complete list:

help[Enter]

GNU bash, version 2.03.0(1)-release (i386-pc-linux-gnu)
These shell commands are defined internally.  Type `help' to see this list.
Type `help name' to find out more about the function `name'.
Use `info bash' to find out more about the shell in general.

A star (*) next to a name means that the command is disabled.

 %[DIGITS | WORD] [&]               . filename
 :                                  [ arg... ]
 alias [-p] [name[=value] ... ]     bg [job_spec]
 bind [-lpvsPVS] [-m keymap] [-f fi break [n]
 builtin [shell-builtin [arg ...]]  case WORD in [PATTERN [| PATTERN].
 cd [-PL] [dir]                     command [-pVv] command [arg ...]
 continue [n]                       declare [-afFrxi] [-p] name[=value
 dirs [-clpv] [+N] [-N]             disown [-h] [-ar] [jobspec ...]
 echo [-neE] [arg ...]              enable [-pnds] [-a] [-f filename] 
 eval [arg ...]                     exec [-cl] [-a name] file [redirec
 exit [n]                           export [-nf] [name ...] or export 
 false                              fc [-e ename] [-nlr] [first] [last
 fg [job_spec]                      for NAME [in WORDS ... ;] do COMMA
 function NAME { COMMANDS ; } or NA getopts optstring name [arg]
 hash [-r] [-p pathname] [name ...] help [pattern ...]
 history [-c] [n] or history -awrn  if COMMANDS; then COMMANDS; [ elif
 jobs [-lnprs] [jobspec ...] or job kill [-s sigspec | -n signum | -si
 let arg [arg ...]                  local name[=value] ...
 logout                             popd [+N | -N] [-n]
 printf format [arguments]          pushd [dir | +N | -N] [-n]
 pwd [-PL]                          read [-r] [-p prompt] [-a array] [
 readonly [-anf] [name ...] or read return [n]
 select NAME [in WORDS ... ;] do CO set [--abefhkmnptuvxBCHP] [-o opti
 shift [n]                          shopt [-pqsu] [-o long-option] opt
 source filename                    suspend [-f]
 test [expr]                        time [-p] PIPELINE
 times                              trap [arg] [signal_spec ...] or tr
 true                               type [-apt] name [name ...]
 typeset [-afFrxi] [-p] name[=value ulimit [-SHacdflmnpstuv] [limit]
 umask [-p] [-S] [mode]             unalias [-a] [name ...]
 unset [-f] [-v] [name ...]         until COMMANDS; do COMMANDS; done
 variables - Some variable names an wait [n]
 while COMMANDS; do COMMANDS; done  { COMMANDS ; }

Since a good system must allow the use of different shell, often there are executable program which are equivalent to the internal di shell commands that are already available. For example you might find an echo program, even if the Bash shell offers it as an internal command.

help echo[Enter]

echo: echo [-neE] [arg ...]
    Output the ARGs.  If -n is specified, the trailing newline is
    suppressed.  If the -e option is given, interpretation of the
    following backslash-escaped characters is turned on:
        \a      alert (bell)
        \b      backspace
        \c      suppress trailing newline
        \E      escape character
        \f      form feed
        \n      new line
        \r      carriage return
        \t      horizontal tab
        \v      vertical tab
        \\      backslash
        \num    the character whose ASCII code is NUM (octal).
    
    You can explicitly turn off the interpretation of the above characters
    with the -E option.

What you see above is the syntax of the internal echo command, whereas the executable echo program might be slightly different:

/bin/echo --help[Enter]

Usage: /bin/echo [OPTION]... [STRING]...
Echo the STRING(s) to standard output.

  -n              do not output the trailing newline
  -e              enable interpretation of the backslash-escaped characters
                    listed below
  -E              disable interpretation of those sequences in STRINGs
      --help      display this help and exit (should be alone)
      --version   output version information and exit (should be alone)

Without -E, the following sequences are recognized and interpolated:

  \NNN   the character whose ASCII code is NNN (octal)
  \\     backslash
  \a     alert (BEL)
  \b     backspace
  \c     suppress trailing newline
  \f     form feed
  \n     new line
  \r     carriage return
  \t     horizontal tab
  \v     vertical tab

Report bugs to <bug-sh-utils@gnu.org>.

589.13.3   Script and execution permissions

In a Unix system, it is easy to develop small program by combining different commands, i.e by preparing a shell script. You can try to enter the file my_script in the current directory with the following content:

#!/bin/sh
echo Hello everybody!

It is a text file that can be easily written by using VI. If this file is saved with the chosen name, i.e. my_script, one can expect to start it by using the following command:

./my_script[Enter]

bash: ./mio_script: Permission denied

As you can seen, the script has not been started. You can check whether the required permissions are missing:

ls -l my_script[Enter]

-rw-rw-r--    1 bloggs   bloggs         20 mar 24 10:54 my_script

You can just add the missing permissions and everything works correctly:

chmod +x my_script[Enter]

ls -l my_script[Enter]

-rwxrwxr-x    1 bloggs   bloggs         20 mar 24 10:54 mio_script

./my_script[Enter]

Hello everybody!

589.13.4   Conclusion

In the Unix systems, often ``commands'' are mentioned in a vague way, to avoid having to distinguish explicitely whether one refers to an executable or to an internal command of the interpreter(the shell).

If one enters a command name without its path, one leaves the search to the command interpreter, which first looks for an internal command, later for an alias, finally for an executable file in the paths listed in the PATH environment variable.

When one develops a program or a shell script, one should remeber to assign the execute permissions to allow it to be run.

589.14   Searches

The searches of files and directories are very important when one use a un file system with many branches as those used in Unix systems.

589.14.1   Find

Files and directories van be searched by name and other external characteristicsm, by using the command find.

find / -name bash -print[Enter]

The above command executes a search of files and directories names bash within all directories that start from the root.

/bin/bash
...
find: /var/run/sudo: Permission denied
find: /var/spool/at: Permission denied
find: /var/spool/cron: Permission denied
...

The file is found, but whenever find tries to navigate a directory without the required permission, it produces an error message.

The searches based on the name can use also wildcard characters, but in this case they must be managed by find and not by the shell, consequently one must do something to prevent a shell action.

find / -name \*sh -print[Enter]

The use of the back slash before the asterisk allows to prevent the interpretation of wildcard characters by the shell. Finally, find receives the correct argument, without the slash before the asterisk.

/bin/bash
/bin/ash
/bin/sh
...

589.14.2   Grep

If one needs to do searches within a file, one can use grep.

grep bloggs/etc/*[Enter]

/etc/group:bloggs::500:bloggs
/etc/passwd:bloggs:Ide2ncPYY1234:500:500:Bloggs Blogg:/home/bloggs:/bin/bash
grep: /etc/skel: Is a directory
grep: /etc/sudoers: Permission denied
...

The result obtained by the previous command, are the names of the files that contain the word ``bloggs'' and the line where it appears. Also in this case there might be files or directories without the required permissions, that cannot be accesses by grep.

589.14.3   Conclusion

The commands find and grep are the foundation for all file searches on the Unix systems. They can be combined together to make searches based on both the external and internal file properties. The subjet is discussed in the chapter ##en-capitolo-ricerche##.

589.15   Disks and file system

The management of disks on the Unix systems looks rather complex when his philosophy is approached by a beginner. The section 587.4.3 has introduced the subject.

The diskettes used for this exercise must not be write protected.

589.15.1   Inizialization

The disk initialization and formatting consists of two phases: the preparation of tracks and sectors and the creation of a file system. The first phase is also known as low level formatting and usually it is done only on diskettes.

Before continuing, you should take the privileges of the root user.

su[Enter]

Password: ameba[Enter]

Before starting the low level formatting, you should check the name of the diskette device on your system, because they can be different on different distributions. We assume that you van use diskettes of 3,5 inches (9 cm) with a format of 1 440 Kbytes.

ls /dev/fd0?1440[Enter]

You might get the name of /dev/fd0u1440 and /dev/fd0h1440, or /dev/fd0H1440 and the usual /dev/fd0h1440. What should be used is /dev/fd0u1440 or /dev/fd0H1440.

We start the low level formatting (we show here an example based on the use of the device /dev/fd0u1440).

fdformat /dev/fd0u1440[Enter]

Double-sided, 80 tracks, 18 sec/track. Total capacity 1440 kB.
Formatting ... done
Verifying ... done

If the executable program fdformat is not available, you should find instead superformat, which can be used in the same way, even if it produces different messages.

If you get the result above, the diskette has been formatted succesfully. We need now to format two additional diskettes.

The diskettes after the low level formatting are not yet ready to receive data in directory and file format. We need to create a file system.

mkfs.msdos /dev/fd0[Enter]

mkfs.msdos 0.3b (Yggdrasil), 5th May 1995 for MS-DOS FS

In this way, we have created a file system of type Dos-FAT on the diskette that previously had been formatted. The message may be different in other installations of GNU/Linux, but this is not important.

After replacing the diskette, you can run the following command in order to create a file system Minix.

mkfs.minix /dev/fd0[Enter]

480 inodes
1440 blocks
Firstdatazone=19 (19)
Zonesize=1024
Maxsize=268966912

After replacing the diskette, you can run the following command to create a file system Ext2.(7)

mkfs.ext2 /dev/fd0[Enter]

Filesystem label=
OS type: Linux
Block size=1024 (log=0)
Fragment size=1024 (log=0)
184 inodes, 1440 blocks
72 blocks (5.00%) reserved for the super user
First data block=1
1 block group
8192 blocks per group, 8192 fragments per group
184 inodes per group

Writing inode tables: done 
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 33 mounts or
180 days, whichever comes first.  Use tune2fs -c or -i to override.

To continue the exercise, you must distinguish the three diskette that have been just prepared, in order top recognise which one uses the file system Dos, which one uses the Minix and which one uses Ext2.

589.15.2   Mounting and dismounting diskettes

In the Unix and similar systems, in order to access a storage unit, its file system must be mounted in the global one. It is not possible to name a directory or a file with a reference to a device. The mount is an operation which links the file system of a storage unit to a directory of the already active file system. The directory that is normally used to mount temporarely external devices is /mnt/.

We start by loading the diskette formatted with the Ext2 format and by mounting it into the /mnt/ directory.

mount -t ext2 /dev/fd0 /mnt[Enter]

Now, the directory /mnt/ has become the start of the diskette.

touch /mnt/super.ultra.mega.macro[Enter]

The command above can be use to create an empty file with a rather long name. If you want, you can copy some files to the diskette.

cp /bin/bash /mnt[Enter]

Usually the prompt of the shell becomes available again before the completion of the writing operations, because there is a ``buffer memory'', or more precisely a cache memory. This is one of the reasons why the diskette cannot be simply extracted at the end of the operations that you have asked to perform.

While the diskette is mounted, it can be considered as a component of the global file system.

ls -l /mnt[Enter]

total 418
-rwxr-xr-x   1 root     root       412516 Dec 28 13:10 bash
drwxr-xr-x   2 root     root        12288 Dec 28 12:37 lost+found
-rw-r--r--   1 root     root            0 Dec 28 13:05 super.ultra.mega.macro

Notice that the diskette contains the file that we have created before, the bash executable that we have copied and a special directory: lost+found/. This is created automatically together with the file system Ext2. Generally it can be removed, if one does not want it. However, its existence can be useful to locate the start of a file system mounted in that point.

We now continue by replacing the diskette with that which contains the Minix file system. In order to do this, you must first unmount the current diskette and then mount the second one.

umount /mnt[Enter]

Now, when the prompt of the shell is presented again, you can replace the diskette.

mount -t minix /dev/fd0 /mnt[Enter]

As an exercise, we repeat the previous operations.

touch /mnt/super.ultra.mega.macro[Enter]

cp /bin/bash /mnt[Enter]

ls -l /mnt[Enter]

total 404
-rwxr-xr-x   1 root     root       412516 Dec 28 13:31 bash
-rw-r--r--   1 root     root            0 Dec 28 13:31 super.ultra.mega.macro

Notice that the Minix file system does not include a lost+found/ directory. Another thing to notice is that the long file name has been written correctly, but the names cannot be longer than 30 characters in a Minix file system.

umount /mnt[Enter]

Finally we repeat the same operations with the diskette Dos-FAT.

mount -t msdos /dev/fd0 /mnt[Enter]

touch /mnt/super.ultra.mega.macro[Enter]

cp /bin/bash /mnt[Enter]

ls -l /mnt[Enter]

total 403
-rwxr-xr-x   1 root     root       412516 Dec 28 14:02 bash
-rwxr-xr-x   1 root     root            0 Dec 28 14:01 super.ult

Since this diskette has a file system Dos-FAT, the result looks different. First of all, the file permissions are not the same as those of the previous examples: basically, all files have the same permissions. The file owner is always root because he is the user who mounted the diskette. The file name is truncated.

If you want to use a DOS;-FAT diskette to store long names, in the same way as you would do with MS-Windows 95/98, you could mount it with a reference to a file system of type vfat, whereas the formatting is done as before.

Before terminating this exercide, we unmount the diskette.

umount /mnt[Enter]

It is useful to remind that a disk cannot be unmounted unless all activities with it have been terminated. For this reason, if the current directory is positioned on a directory which is included in the file system of the disk that one wants to unmount, the operation will not be successful.

589.15.3   Conclusion

The management of storage devices may seem to be complicated until one does not understand its logic. The most important thing is that one cannot retrieve the content of a disk unless this has been mounted and one cannot extract a disk unless this has been unmounted.

These subjects are better presented after the chapter ##en-capitolo-memoria-massa##.

It is useful to remind that the exercise has been done as the root user, therefore, before continuing, it is advisable to go back to a normal user.

exit[Enter]

589.16   Devices

In the Unix systems, the devices are represented by special files that can be found in the /dev/ directory. The direct use of devices is often a delicate operation, which can be done only by the root user. Some exercises in this section are done as a root user and, in this situation, you will notice the prompt of the shell, which is represented in the examples by the symbol #.

589.16.1   /dev/null

The device file /dev/null is interpreted as an empty file for reading and as nothing for writing: whatever is written there is lost. This feature is very useful when a script should not send any output to the user.

ls /bin > /dev/null[Enter]

The command above does not produce any output on the screen because everything is redirected towards /dev/null. You can also check that nothing exists in this file by using the command:

cat /dev/null[Enter]

No output is produced.

589.16.2   Storage devices

The direct access to a storage device is a delicate operation which requires the privileges of the root user.

su[Enter]

Password: ameba[Enter]

The storage devices are processed as if they were files. Actually, a diskette with 1 440 Kbytes is processed as a file with the same size.

In the previous exercises, we have formatted some diskettes and we have copied some file into them.

We want now to create an image file of one of the diskettes that have been prepared before. We insert one of these disks.

cp /dev/fd0 disco.img[Enter]

The diskette that we have copied to the image file has not been mounted yet and it is still unmounted.

ls -l disco.img[Enter]

-rw-r-----   1 root     root      1474560 Dec 28 14:59 disco.img

If one wants to copy the diskette that has been copied to the image file, one can just repalce it with another one, that must have been previously low-level formatted (by fdformat for instance, or with similar commands in your operating system) and then copy the image file onto the device file corresponding to the diskette.

We replace the diskette and execute the following command.

cp disco.img /dev/fd0[Enter]

The diskette now contains is an identical copy of the original diskette.

589.16.3   Conclusion

The direct access to device files is a method especially used for the duplication of disks (usually diskettes) in order to keep all data that they originally contained. This approach is used to transfer and reproduce diskettes of different operating systems, and it is what one usually does when one must prepare the first GNU/Linux disks starting from Dos.

589.17   References

Appunti di informatica libera 2003.06.29 --- Copyright © 2000-2003 Daniele Giacomini -- daniele @ swlibero.org


1) Translation last update on 2003.06.19 from Mario Pesce mario @ datamission.co.uk (original chapter was 7).

2) In this chapter only ``commnds'' are referred to, because in this part of the document, addressed to beginners, it is advisable to avoid complicating things too much and to create confusion. The full phylosophy of this chapter should be seen in this perspective.

3) This is clearly a relative path

4) In the examples, we assume that one can access the personal directory of another user. However this possibility depends on the permissions.

5) To be precise, it would be better to use the command echo, which however has not yet been explained.

6) In this case the current directory corrente is moved at the start of the list, by leaving it also at the end, even if this is useless.

7) It is not possible to create on a diskette the extensions required by the format Ext3.


It should be possible to link to this page also with the name practical_exercises.html

[next] [previous] [top] [last] [indice generale] [violazione GPL] [translators] [docinfo] [indice analitico]


aa - ab - af - ak - als - am - an - ang - ar - arc - as - ast - av - ay - az - ba - bar - bat_smg - bcl - be - be_x_old - bg - bh - bi - bm - bn - bo - bpy - br - bs - bug - bxr - ca - cbk_zam - cdo - ce - ceb - ch - cho - chr - chy - co - cr - crh - cs - csb - cu - cv - cy - da - de - diq - dsb - dv - dz - ee - el - eml - en - eo - es - et - eu - ext - fa - ff - fi - fiu_vro - fj - fo - fr - frp - fur - fy - ga - gan - gd - gl - glk - gn - got - gu - gv - ha - hak - haw - he - hi - hif - ho - hr - hsb - ht - hu - hy - hz - ia - id - ie - ig - ii - ik - ilo - io - is - it - iu - ja - jbo - jv - ka - kaa - kab - kg - ki - kj - kk - kl - km - kn - ko - kr - ks - ksh - ku - kv - kw - ky - la - lad - lb - lbe - lg - li - lij - lmo - ln - lo - lt - lv - map_bms - mdf - mg - mh - mi - mk - ml - mn - mo - mr - mt - mus - my - myv - mzn - na - nah - nap - nds - nds_nl - ne - new - ng - nl - nn - no - nov - nrm - nv - ny - oc - om - or - os - pa - pag - pam - pap - pdc - pi - pih - pl - pms - ps - pt - qu - quality - rm - rmy - rn - ro - roa_rup - roa_tara - ru - rw - sa - sah - sc - scn - sco - sd - se - sg - sh - si - simple - sk - sl - sm - sn - so - sr - srn - ss - st - stq - su - sv - sw - szl - ta - te - tet - tg - th - ti - tk - tl - tlh - tn - to - tpi - tr - ts - tt - tum - tw - ty - udm - ug - uk - ur - uz - ve - vec - vi - vls - vo - wa - war - wo - wuu - xal - xh - yi - yo - za - zea - zh - zh_classical - zh_min_nan - zh_yue - zu -