Вы находитесь на странице: 1из 10

Introduction to Linux

The command-line interface


A command-line interface (CLI) is a type of interface, that is, a way to interact
with a computer. Window systems, punched cards or a bunch of dials, buttons
and blinking lights are other types of interfaces. In CLIs, also known as consoles,
terminals or shells, we type instructions that the computer may interpret and
execute.
In this tutorial we will cover the basic usage of the CLIs found on UNIX-
like operating systems. Although nowadays most of these systems have also
graphical user interfaces (GUIs) like in Windows or Mac OS, CLIs remain still
very popular as they permit to do certain tasks much more eciently.
Throughout the tutorial, you will nd grey boxes containing things to be
done: execute commands, answer questions, etc. The oval boxes are supposed
to be used as a quick reference, containing information that you will need to go
back to often, such as explanations about the dierent commands.
Let's start then!

The console tells us that it is ready to get instructions (commands ) by show-


ing the command prompt :

sergio@silicon:~$

Commands are introduced by typing some characters and pressing the Enter
key.

B Enter the command echo Hi! in the console.

 
• echo STRING
Displays the line of text given in STRING.
 
Commands consist of one or more chunks or tokens separated by spaces.
The rst token is the command itself, that is the instruction to be executed.
The rest of the tokens are arguments, which give extra information on how the
instruction should be executed. They can be options, le names, numbers...
This depends on each program.
Notice that the CLI is case-sensitive! This means that Echo, ECHO, etc, will
not work!
∗ Actually it should read, "Introduction to command-line interfaces on UNIX-like operating

systems". For more information on UNIX, Linux, GNU, etc., you can have a look at their
Wikipedia pages.

1
Figure 1: Example of a UNIX le system.

B Enter the command ls

B Enter the command ls -l. What is ls? What is -l?


#
• ls [DIRECTORY]
List the content of DIRECTORY. If no DIRECTORY is given, show the contents of
the current directory.
Some useful options: -l, long format. -a, show hidden les. -t, sort by modi-
cation time. -h Show le sizes in human-readable format.
" !

Moving around the directory tree


All information is stored in les. A le may contain a text le, a picture, a
program, etc.The command ls -l gives a lot of information on each le. For
instance:

-rw-rr 1 sergio users 3397 2011-05-11 17:03 xmatrix.F90


The rst column describes the le permissions. In this case, it says that this
le can be read by all users and written by its owner this will be discussed later.
We can safely ignore the meaning of the second column. The third column is
the owner, and the fourth the group to which the le belongs to. The fth is the
size of the le in bytes; using the -h option will show it in kilobytes, megabytes,
etc. The sixth and seventh columns are the timestamp (last modication time).
Directories are le containers. Directories can also be contained in other
parent directories, which can be contained in their own parent directories, and

2
so on. Everything is contained in a master directory, referred as root, denoted as
/. In Figure 1 there is an example of a le system. The root directory contains
three subdirectories:home, usr and media. home contains three subdirectories,
graham, john and terry. graham contains two les, parrot.avi and spam.txt.
The extensions of the les, avi and txt, suggest that they are (most likely, but
not 100% sure!) a video and a plain text le, respectively.

B List the contents of the root directory (ls /).

When we use a terminal, at any given moment we are at a given directory,


called current working directory.

B Enter the command pwd


 
• pwd
Show the current working directory.
 
When we open the terminal, the current directory is our home directory,
whose location is commonly /home/<USERNAME>.
 
• cd [DIRECTORY]
Change working directory to (go to) DIRECTORY. Executing the command with
no arguments (that is, only cd) goes back to the home directory.
 

B Change to the root directory (cd /) and list its contents (ls).

B Execute cd home. List the contents of the directory.

B Execute cd home again. Why didn't it work?

B Go back to your home directory.

Before we proceed, a warning!: blank spaces should be avoided in names in


UNIX-like operating systems .
1 mkdir My Documents would be interpreted as
create two directories called My and Documents! Use underscores (_) instead.
 
• mkdir DIRECTORY
Create a new directory, called DIRECTORY.
 
1 There is a way to use blank spaces in names, but it will not be shown in this tutorial.

3
B Create a directory in your home directory called dir.

B Go into dir, and create another directory inside called subdir. Go back to
your home directory.

We can also refer to les and directories in other directories by giving the path
to them, which is the names of the parent directories joined by slash characters
(/).

B Change into the subdirectory that you just created using cd dir/subdir.

The current directory is referred as  ., and the parent directory as  ...
The home directory can be referred as  ∼.

B Go to the previous directory (cd ..).

Files and directories are uniquely identied by their full address, known as
absolute path : it is the list of its parent directories in order, separated by /.

B What is the absolute path of subdir? What is the relative path to /etc/X11
from your current directory? List the contents of that directory using only one
command.

B Auto-completion is a neat trick that most modern shells can do. Type
ls /h, and before pressing Enter, press the Tab key ( →−
−−−
→ ). Nice, isn't
it?

Before you jump to the next section, make sure that you understand:

ˆ What are les and directories.

ˆ How directories and les are organized in a tree structure.

ˆ How to go to any directory.

ˆ What are relative and absolute paths.

ˆ How to refer to any le or directory you want.

Viewing and editing text les


Let's start by downloading an existing le from the internet.

4
B Download the text le located at http://www.chem.helsinki.fi/~sergio/
menu

• wget URI
Download the resource located at URI.

The le menu is a plain text le. That means that it only contains a bunch
of characters. Text les are not the same as a le produced by a text processor,
like Microsoftr Word documents or similar! There is no format, pages, etc.:
only text.
The command cat is the most simple way to see the contents of a text le.
It simply dumps the le onto the console. The name comes from concatenate,
because it can be used to join several les.

B Display the content of menu using cat.


 
• cat FILE[s]
Print the content of FILE[s] on the console.
 
Another convenient program to visualize text les is less. Navigate with
↑ ↓ , Q to exit, H for help. This method is more convenient
to visualize longer les.

B Display the content of menu using less.


 
• less FILE
Display the content of FILE on the console.
 
This is all very nice, but how to edit text les? As text editors are one of the
most important tools, a plethora of alternatives has ourished with the years.
In this course, we will use nano, a very simple and light-weight alternative.
 
• nano [FILES]
Simple text editor. If no FILES are given, a new blank le is opened.
 
nano has an intuitive interface, with the most used commands shown in
the bottom part of the console. The ^ symbol stands for the Ctrl key: for
instance, to exit, press Ctrl + X .

5
B Edit menu. Make some changes to the le, save and exit. Examine the le
with less

B Create a new text le containing a short line of text. What is its size? Use
ls -l for this. How is the size related to the text you wrote?

Once you are more familiar with text editors, you should try to nd which of
the many ts best your needs and preferences. They have dierent capabilities,
but many of them are specially adapted to the needs of programmers . Some
2
have familiar graphic interfaces, such as Kate or gedit. Vim and Emacs are con-
sidered to be the most powerful editors by many, and with a long development
history and a large user community, they have plenty of add-ons and extensions
available. This has a cost: they are not the most intuitive and easy to use for
beginners, which is specially true for Vim.

Working with les


In this section, we will discuss how to work with les, that is, how to create
them, rename, copy, delete...
Files can be copied, renamed, moved, deleted, etc.
#
• cp SOURCE[s] DEST
Copy SOURCE into DEST.
If SOURCE is a le and DEST is a directory, SOURCE is copied into DEST.
If there are multiple SOURCEs, DEST must be a directory.
If SOURCE is a directory, the option -r must be used, i.e. cp -r SOURCE DEST.
" !
 
• mv SOURCE[s] DEST
Move SOURCE into DEST. This command is also used to rename les.
If SOURCE is a le and DEST is a directory, SOURCE is moved into DEST.
If there are multiple SOURCEs, DEST must be a directory.
 
 
• rm FILE[s]
Deletes FILE[s].
If any of FILE[s] is a directory, the option -r must be used.
 
2 Who swear by their favorite text editors. See http://xkcd.com/378/.

6
B Familiarize yourself using the previous commands on the directories you have
created and the menu le:

ˆ Make a copy of a le with a dierent name.

ˆ Copy a le into a dierent directory.

ˆ Rename a le.

ˆ Move a le into a dierent directory.

ˆ Remove a le.

ˆ Remove a directory.

ˆ Copy, move and delete several les at the same time.

The touch command might be useful to create dummy les to play around.

 
• touch FILE[s]
Create empty FILE[s].
If FILE[s] already exist, modify timestamps (the times shown by ls -l). This
pretends to have modied (touched) the le.
 
Wildcards are special characters that can be used to refer to multiple les at
the same time. ? can be used to substitute any single character, and * for any
string of characters.

B Create a new directory. Go into it, and create three les called file1, fileZ
and file.txt. What is the output of ls file?? And ls file*?

B What will happen if you enter rm *? Think twice before doing this!

As with blank spaces, don't use special symbols ( } '"`<>|;()[]? #


$^& = ) for le names.

Help!
So many commands already! You must be wondering how people manage to
remember all this. Practice helps, especially when you need CLIs often. But
the truth is that few remember all details all the time, and everyone needs some
help at some point!
There are two main ways to get help: the help option and the man pages.

7
 
• --help option
A command run as COMMAND --help, instead of doing what the command nor-
mally does, will display a brief explanation of its usage and purpose and a
summary of its options.
 
#
• man COMMAND
Shows the man pages (the reference manual) of COMMAND.
This is commonly the most detailed information that can be found about the
command.
man uses by default less as front-end to navigate the le.
" !

B Look at the documentation of some command using the help option. Then,
have a look at its man page.

Note that not all commands necessarily support neither option.

Redirecting input and output


Programs usually wait for information (input) to be given to them. The standard
input is the channel the information is expected to come through. In our case, it
is the keyboard. Likewise, programs produce output, which we normally expect
to see on the console (standard output).

B Open the shell calculator bc and run some calculations. What is output and
what is input?

 
• bc
Simple calculator. Exit with quit.
 
The output of a command can be saved to be used for some other purpose
later on. This is called output redirection, and is done using the > operator.
 
• COMMAND > FILE
Redirect the output of COMMAND into FILE.
 

B Run bc > out, run a few calculations, and exit. Examine the content of the
newly created le out.

If the le you are redirecting to already exists, the > operator will overwrite
its contents. The  operator instead appends the output to the end of the le.

8
 
• COMMAND  FILE
Same as >, but append to the end of FILE instead of overwrite.
 

B Test the dierences between > and  rewriting an existing le, appending new
output to an existing le, etc.

Input can be also redirected. Imagine that you have to run a program
many times, typing always the same input. We can redirect input using the <
operator, so that a program takes the information it needs from a le instead
of the keyboard.
 
• COMMAND < FILE
Use the contents of FILE as input for COMMAND.
 

B Create a text le input containing several arithmetic operations, one in each
line. Run bc so the operation are read from input.

Input and output can be redirected simultaneously, so that input is read


from a le and output is written into another one.

B Test simultaneous input/output redirection using bc < input > output.

In some cases, we produce some output with a program, which is then fed
to another program as input. This can be done easily using pipes.
 
• COM1 | COM2
Pipeline: execute COM1 and redirect its output as input for COM2.
 

B What does the ls /etc | less command do?

Compiling C programs with gcc


This is an example of a program written in C:

#include <stdio.h>
int main(){
printf("Hello,world\n");
}
Computers only understand machine code, which, as you might have guessed,
is composed of 1s and 0s. In order to translate the program into something the

9
processor can understand, we use programs called compilers. For this course,
we will use , the GNU C compiler.

B Write the C program shown above into a text le hello.c.

B Compile the program running gcc hello.c -o hello

B Run the program (./hello)

In order to run the program, we need to give the path to it. For something
that we just compiled, it will be in the same directory (.), so we need to write
./ before the name of the program.

10

Вам также может понравиться