Shell Tutorial

Talking to GNU / Linux through shell

The shell or command interpreter, as we said before, is an interface with our operating system. Thanks to him we can give orders and commands necessary for our system to perform computer tasks that need. We must not confuse the command interpreter with the operating system. This is just a program that will mediate between us and the system kernel. The shell can be both graphic (eg The X-Window interface), and text (eg the bash).

In this chapter we discuss the issue of single-level shell and special text will see a command interpreter that its usefulness and its wide acceptance, is it more used both in Un * x like GNU / Linux. As we shall see, the shell does not only have the task of interpreting our mandate, is also a powerful programming language that will be very useful when developing scripts (script) to automate our tasks. DOS users will be familiar with the use of batch files (. Bat) or rather called “batch”.

There are several types of UNIX shell in which the most famous and important are the “Bourne Shell” (sh) and the “C Shell” (csh). The Bourne shell, use a command syntax used in early UNIX systems, such as System III. Bourne shell name in most A * x is / bin / sh (sh shell). The C shell has a syntax very similar to C programming language and find it as / bin / csh. The most commonly used on GNU / Linux, as stated above, is the bash for “Bourne Again Shell and find it in / bin / bash. Bash has all the functionality with advanced sh C Shell, so any script writing for a sh shell will run perfectly on it. If what is preferred is the use of shell based on the C language, in GNU / Linux can be found in the tcsh / bin / tcsh, which is an extended version the C Shell. tastes of the users are the ones who decide which shell will be used, so you can set for each user with a different shell and not affect the operation of programs like ls, cat or cp. Only vera affected the functionality of a script that is ready to run with a particular shell, which we will see how it can be corrected to see shell script programming.

For more information about each of these shells is recommended to read the manual pages each, giving very detailed information of these.



We’ll talk about some very useful feature which will ease the work, both in sh and bash. One of the features that have the shells is to use wildcards to replace parts of files. With this, it could refer to a file using special characters such as “*” or “?”. Suppose you want to list all files that contain the letter “ñ” in our directory. We will use the ls command

[Shrek @ Swamp: ~] $ ls * ñ *
This command interpreter as if we will see it lists all files that begin with none, one or more characters, they had a letter “ñ” and end with none, one or more characters.

[Shrek @ Swamp: ~] $ ls
texto.form heart hello manti.form
[Shrek @ Swamp: ~] $ ls h *
hello heart
As you can see we also useful if you know how the file starts but not how it ends. What our command interpreter is doing is replacing the “*” with any possible combination to match the files we have in the directory where you are looking. If using only the “*” with the ls command, this play being searched every possible combination and list everything as if he were trying to run the ls command only

[Shrek @ Swamp: ~] $ ls *
texto.form heart hello manti.form
This process is called “globbing” and is performed by the shell. This is very important because the commands like ls never see the “*” in its parameter list, is the shell expands the wildcard to include all file names that fit. This means that after the order is given

[Shrek @ Swamp: ~] $ ls h *
is expanded to obtain

[Shrek @ Swamp: ~] $ ls hello heart
Another wildcard is the “?”. This expands wildcard only a single character. Then ls? display all file names with one character. Instead the ls command hol? hello file will show.

[Shrek @ Swamp: ~] $ ls ho? To
[Shrek @ Swamp: ~] $ ls h????
These wildcards allow us to refer to more than one file at the same time and in conjunction with previously learned commands may be useful to perform our tasks easier.

Running commands one after the other

Suppose you need to run a command and immediately after another. In stock form what we would do would be to run the first command and once this is finished, you would execute the second. There is a second way to do this and is using the “;” immediately after the first command and then put the second command. This would achieve that will run the first command and the end of the second run.

[Shrek @ Swamp: ~] $ ls
texto.form heart hello manti.form
[Shrek @ Swamp: ~] $ date
Wed July 14 15:15:25 ART 2004
Using the “;” will

[Shrek @ Swamp: ~] $ ls, date
texto.form heart hello manti.form
Wed July 14 15:15:25 ART 2004

This point is well clear it before you start to see features and script alias to avoid complications and confusion. In GNU / Linux there are three types of quotes: the double quotes (“), single quote (‘) and reverse or tics backquotes (`).’ll Start with backquotes. These indicate to the shell that will have to replace what is enclosed them with the result. Suppose we want to see only today. then you would type the command

[Shrek @ Swamp: ~] $ date +% d
Now, every time we would see this day would have to enter this command again. If we assign an environment variable to the result, we would only have to show this variable.

[Shrek @ Swamp: ~] $ DIAHOY = `date +% d`
[Shrek @ Swamp: ~] $ echo $ DIAHOY
Keep in mind that to assign a value to a variable we have to just put a name followed by the “=” and then we want to put inside. In contrast to show it we will precede the dollar sign “$”. This would be equal to putting

[Shrek @ Swamp: ~] $ DIAHOY = 15
The only thing the shell does is expand the command to only store the result of this.

The other type of quotes, the simple (‘) tells the system not to make any expansion.

[Shrek @ Swamp: ~] $ DIAHOY = `date +% d ‘
[Shrek @ Swamp: ~] $ echo $ DIAHOY
date +% d
What you get is exactly what we assign to the variable since I do not do any expansion shell and all he was assigned the string ‘date +% d’ to the variable DIAHOY.

The last type is the double quotes, this has almost the same functionality as the quotes but with the caveat that what is included within these will be subject to expansion by the shell, with the characters with special meaning tics inverse (`), the dollar sign ($), the slash (\) and the same double quotes (“). For example we could enter the following command

[Shrek @ Swamp: ~] $ echo “` date `”
Sat April 15 14:17:01 ART 2000

Using alias gives us the ability to reference a command with a different name. The substantial difference we can find the shell script, the script is to run a subshell launched first as a child process of the shell that is running at the time. Instead an alias works in the shell process being executed internally with subsequent speed this gives by not having to create a new process or to search the hard drive. Of course you can use a set of commands to create a more complex. With scripts you can do the same and we will see later, but for simple and short commands are not needed. The aliases belong to each user and can configure it for your convenience.

Suppose we want to see only the time every time we ask the system and we do not want to put the date command with modifier every time I want to do. What we will do is create an “alias” to the command “date” with the appropriate modifier. For this we have the alias command, followed by arguments that allow us to create one without arguments will show that we have configured aliases.

[Shrek @ Swamp: ~] $ alias hour = `date +% r ‘
[Shrek @ Swamp: ~] $ time
2:45:04 PM
Now this work while we are in the system, since these data are loaded into memory and leave the system will be lost. For every time you enter the system continue to function aliases we add them to a file, which appears as hidden in each user directory, called. Bashrc or if it is required that the alias works for all users in the / etc / bashrc. This file is read by the / bin / bash every time you login. It will have to put the line alias in the same way you would in the command interface.

Completed line

You can make the complete shell command line when you enter the first few letters and press Tab. This property is also useful to expand the path into a particular directory. Suppose that in the / home there is a subdirectory named / shrek

[Shrek @ Swamp: ~] $ cd / home / shr
If you press the Tab key will complete the line in / home / shrek. If there is more than a directory that start with “shr”, the shell would announce with an audible signal “beep” that there are more than a coincidence, and pressing the Tab key again show a list of all directories that have “shr “at the beginning. If the list exceeds the motrar catid lines to the console, first ask us if we want to see the number “X” of possibilities. As an example we could cite command autocompletion. Pressing the Tab key without entering anything before, the shell would show first that there is an “X” number of possibilities and pressing again would show a list of all commands that are achievable.


Many times it happens that when trying to enter a command that we realize has no effect and it gives an error in it shell. Perhaps evil is entered, but may not possess the directory containing the command in the “search path” or PATH. THE PATH is an environment variable that contains a predefined set of directories in which the shell searches for the command or program to run. This saves time because the system will not have to search all the directories the program to run. For this system, if the directory is not on the PATH, you can run the program to give you the exact path where you are.

The PATH environment variable is initialized with a default value in the / etc / profile that can only be changed by the “root” and serves as a reference for all users. Each user has a hidden file called. Bash_profile or. Profile, which assigns initial PATH addition, any other modifications exclusively for him. You can also completely change this variable.

Returning to the full path specification, previously said that the files referenciaban this way, but programs can also be referenced in the same way. If we give the full path we run the program, if you have the appropriate permissions, regardless of the value of the PATH variable. As an example, if we run the program date, referencing it with a full path, the syntax is

[Shrek @ Swamp: ~] $ / bin / date
Wed July 14 15:15:25 ART 2004
Surely the / bin directory is on our way, this serves only as an example.

There is another way to run the program, and is referring to its relative path, which is the relative path to the directory where we stand today. For this we must know how to reference the current directory is by “.” and to its parent directory with “..” (Mentioning commonly as “point” and “point – point”). Since directories are divided by a “/”, it could refer to a file in the parent directory .. / file. Thus, if you wanted to refer to a file that is located two levels above us, its relative reference would be .. /.. / File.

Something that differs in how to run the programs on GNU / Linux and DOS, is that the latter seek first the file to run in the current directory and then in the search path. However in GNU / Linux, only look at the route.

No problem run a file that is in the current directory as this is incluíido on the road, but for safety, should be added as the last directory in the path, at least in the “root” because if a user create a malicious file that was in the directory where the root user is standing at the time, and named him “more” when the root run this command would have catastrophic results. However, if the current directory is at the ends of the path, execute first which I found in the / bin rather than it is in the current directory. Similarly to directly execute a program that is in the directory where we stand now could enter the relative path to this, putting the reference to the current directory “. /” The program. To run the hello program is in the directory where we stand today

[Shrek @ Swamp: ~] $. / Hello
Hello friends!
Do not look for the “hello” in your system, I have not distributed yet developing as this: ^).

Environment variables

Regardless of shell you are using, you will have what is called “environment variable” or “environment variable”. These variables are as we find in any programming language. This is so this way it could also be accessed from the scripts we believe. To distinguish the command, the variables are put in uppercase. When you log in, there are some of these variables are already assigned. To view these variables and their contents has the “set” command, and to view the contents of one of these variables only have to use the command “echo” followed by the variable name with a “$” prefix. Eg echo $ LOGNAME, so get the user name.

Following the search path or PATH, this is stored in a variable called “$ PATH”, so if you type “echo $ PATH” we will see something like this

[Shrek @ Swamp: ~] $ echo $ PATH
/ Usr / local / bin :/ bin :/ usr / bin :/ usr/X11/bin :/ home / shrek :/:.
Note that the last exponent of the path is the current directory we indicated in the previous section on “search path”. As you can see each of the directories are separated by “:” and lastly is the reference to the current directory we talked about earlier. Another important variable is the “prompt” which is neither more nor less than the sequence of characters that appear just before we enter the command interface. The environment has 4 bash prompt’s, “PS1”, “PS2”, “PS3” and “PS4”. These variables have a reason. The name “PS1” is the main prompt is what we see at startup. The “PS2” is displayed if the entered something beyond the line and goes to the next. Its default value is “>”. You can check by entering the “\” on the line that we are entering, which will move to the next line. The “PS3” appears when you use the “select” command from the interface. The “PS4” appears when performing a command track. The prompt and most environment variables can be modified with the “export”, we can modify the contents of the variables.

[Shrek @ Swamp: ~] $ export SECONDS = 0
[Shrek @ Swamp: ~] $ echo $ SECONDS
The variable $ SECONDS count the number of seconds since we entered into the system, with this mandate, we set to “0”. There are variables that can not be changed, such as UID, EUID or PPID, (is a breakdown of the most useful variables in Table 2). Returning to the prompt, this can be changed so that, for example, we show the user name followed by “@” and the name of the system, with the help of special characters.

[Shrek @ Swamp: ~] $ export PS1 = ‘[\ u @ \ h: \ w] \ $’
Shown in the table special characters prompt.

Table 1. Special characters of the variable PROMPT

Representing Character
\ T The current time in HH: MM: SS.
\ D the date in “Weekday Month Date”, for example, “Sun February 4”.
\ N Line.
\ S delshell name.
\ W the current directory.
\ W the basename of the current directory. For example, the / home / shrek, the base name is Shrek.
\ U Username.
\ H machine name.
\ # The command number of this command.
\! Position in the command history for the current command.
\ $ If the EUID is 0 (root), the character ‘#’. Otherwise the character is ‘$’.
\ \ The backslash.
\ Nnn the character corresponding to the octal number nnn.
\ [Begin a sequence of non-printing characters as escape characters or control sequences. These characters can be used to define colors.
\] End of the sequence of non-printing characters.
Table 2. Common Variables

Variable Definition
PPID identification number of the parent process of the command interface.
PWD The current working directory, set by the cd command.
OLDPWD previous working directory set by the cd command.
REPLY When using the bash read command with no arguments, this variable contains the contents of the line read.
UID identification number (ID) of the user, set at shell startup.
EUID Effective user ID, initialized at shell startup.
BASH Full name, including the path, of the file that is executed to launch the shell.
BASH_VERSION Bash version number.
SHLVL Shell level. Increases its value by one each time you launch a new command interface.
RANDOM Each time this variable is invoked to get a random integer. The sequence of random numbers provided by RAMDOM be initialized simply by assigning a new value to this variable.
SECONDS keeps the number of seconds that have elapsed since the shell executed. If we assign a value to this variable, the account indicate the seconds since the allowance, plus the value assigned.
LINENO When referring to this variable from a script, indicates the line in the script in which he is referring to, considering that the first line is numbered 1. If invoked from the interface command, the value returned is the number of the command line that executed since the beginning of the command interface.
HISTCMD contains the position within the command history file that occupies the current command.
HOSTTYPE is a text string describing the type of machine on which bash is executing.
HOSTNAME Hostname.
OSTYPE is a text string describing the operating system on which bash is running.
PATH The search path for commands. It is a sequence of directories to locate programs, separated by a colon (:). The command interface walk that list looking for in the order given that we want to execute commands.
HOME root directory of the current user. This is the argument used by default when you run the cd command without specifying any.
CDPATH is the search path for the cd. It has a structure similar to the PATH variable. Instead, it indicates where to look for the directories specified as arguments to the command. As a typical example, might contain: ~ :/ usr.
When MAIL contains the name of a file, it checks bash the arrival of new mail alerts if it occurs.
MAILCHECK Determines the time interval in seconds that will bash to check for new mail.
MAILPATH Like PATH and CDPATH, this variable contains a list, in this case, of files that should be checked for the possible arrival of mail. You can enter a specific message for incoming mail into different mailboxes using the ‘?’ as a separator between the file and the message. In that case, the $ _ variable will get the mailbox name. An example: MAILPATH = ‘/ var / spool / mail / nlucas? “You have mail”: ~ / mail / mailbox? “Has come something $ _”‘
Value of primary prompt PS1. Table 1 shows the values ​​that can be expanded.
Value of the secondary prompt PS2. This prompt is displayed when we break a line in the command prompt to continue typing on the next line of the screen.
Third PS3 prompt value. This prompt is used only by the select command.
PS4 prompt value and last quarter. Only when this is used to monitor the commands being shown to indicate the steps by which you are running your command. To enter the tracking mode, just run set-x. Then we will see how we execute each command expands, showing the substitutions that are made with aliases, variables, etc..
Contains HISTSIZE he number of commands to store in the command history.
HISTFILE contains the file name that is stored in the command history. By default it is the file ~ /. Bash_history.
HISTFILESIZE maximum number of lines that can contain the history file. Consider that a command can span multiple lines.
PROMPT_COMMAND If this set contains the command to execute before presenting the prompt.
Indicates how many times has IGNOREEOF receiving the EOF character (End Of File, or pressing the Ctrl-D key) before leaving bash. If the value is not numeric, it defaults to 10. If not selected, just one touch.
TMOUT If it contains a value greater than zero indicates the number of seconds that can be without entering a command to the shell. After this time, the command interface closes.
FCEDIT path and name of the editor used by default for the command fc. Default is to use Vi.
Suffix List fignore files were ignored when trying to complete a file name from bash. The list will consist ignored suffixes, separated by a colon (:). For example 0.0:. Tmp
This variable EDITOR many programs seek the path and name of the editor to use. The default used is the Vi editor. Some of the programs that make use of this variable are crontab (with-e), edquota and many others.
TERM contains the terminal type. This variable is important because some terminal types are not compatible with some programs.
Using regular expressions and metacharacters

We begin by expanding the use of wildcards that antesmencionamos (* and?). It is very common to use this kind of caracterespara the shell to expand to cualquiercarácter matching in the case of “?” And any string of characters, in elcaso of “*”. The use of these and we have defined earlier And only display function use in regular expressions.

The regular expressions are a set of rules that expand cumplirsese to be usable. For this you use metacharacters otrotipo also “[]” where the characters will be replaced introduzcandentro to complete the command. Suppose quequeremos edited with the program saw carta.1 files, carta.2, carta.3, carta.4 and carta.5. We can use both the? * paraeditarlo like. But it can also be used the series of numbers from 1 to 5 enclosed within square brackets ([]).

[Shrek @ Swamp: ~] $ vi letter. *
This editaríamos all files from carta.1 to carta.5.

[Shrek @ Swamp: ~] $ vi letter. [12345]
With this expression, the shell will expand to cadauno of the characters between the brackets to take ellugar that corresponds to the name of the file to edit. Â But what would happen if you just want to edit the file carta.1, carta.2 and carta.5? We could use either the character “*” or the “?” to do so in a single step, but if we can use the regular expression in this way

[Shrek @ Swamp: ~] $ vi letter. [125]
With this, and because the shell interprets ofa single character at a time, only the files be edited carta.1, carta.2y carta.5. The numbers will be taken inside the brackets individual comocaracteres.

The usefulness of regular expressions is very large, and it is only existencasos use that can be performed untrabajo. Regular expressions may be used, along with otroscomandos also to identify groups of characters in a text yrepresentarlos as requested. For example, using the grep command, which coincidentally means Global Regular Expression Print will podrábuscar within a text string is required and display on screen. Suppose you need to display all lines that have the word letter on file documents

[Shrek @ Swamp: ~] $ grep letter documents
What we will return the lines that have the word letter, even those who are between their lyrics a group of characters that is equal to that sought, such “letters” or “banner”. Now, what if the word were written letter with the first character capitalized. Then grep not show, for this we could use a regular expression in this way

[Shrek @ Swamp: ~] $ grep [Cc] arta documents
If what we need is to look for lines that start with the word letter, both the “C” in uppercase or lowercase would use the caret symbol (^) and the command is

[Shrek @ Swamp: ~] $ grep ^ [Cc] arta documents
This indicaríamos that displays all lines that they had as the first word “letter” as the first letter in uppercase or lowercase. If what you want is to show all the lines of documents that ended with the word “letter”, would have to use the role of the symbol “$” (we had seen that was used to reference an environment variable) in the regular expressions, placed at the end, indicating that this must be looked for at the end of the line. First we will assign the expression to a variable for the command more readable and see the two functions using the $ symbol

[Shrek @ Swamp: ~] $ VAR = ^ [Cc] arta
[Shrek @ Swamp: ~] $ grep $ VAR $ documents
We explain the use of regular expressions with the grep command only, but there is a number of opportunities to use the commands. It will be seen later that can be widely used in the Vi editor and make us very easy to work with it.

Command interpretation

We have seen the use of a number of common applications comandosjunto these, but of necessity poderentender the method by which these commands are interpreted by elshell to take a little more time understandings elaborarnuestros own script and programs. The first thing we can come to find out, is the order in which commands are interpreted. Leave from the base that can run more than one command on one line. This is achieved by separating them with a semicolon (;).

The first thing the shell does is divide these commands into what is called “tokens”. Each token is a command, along with its arguments, to execute. Once the shell can know how many tokens there, determines its syntax. If there is an error at this point, none of the tokens will be executed and the shell will warn of a possible syntax error. If the syntax is correct, start the interpretation of commands. From here the shell is see if any of the tokens is actually a function of the shell itself. If so, this will be expanded before being executed. Then expand the alias. If any of the tokens is actually an alias, either created by the user or not, this will expand before running. If the alias calls another alias, this will also expand before running. Once you have expanded aliases and shell functions begin evaluating the variables and replaced with its value. At the end this will expand any wildcard used expanding the file name or command to match according to the above rules. Now, although most of the evaluated command, the shell will still have to see if the first of the tokens corresponding to a shell command or an external program. If this happens, you will need to check the search path. Then assess whether there is any redirection or piping, tem we will see more in detail in the next chapter, for which the input or the output of a command redirected elsewhere. Once parsed the entire command or set of commands to a minimum, the shell will back itself through the system call fork () to run the script. This copy is a child of the shell and shell-dependent originated. After this, the child shell, use a named system call exec () to execute the corresponding binary. Although who runs it is actually the child shell, we must remember that the father is still in memory waiting for the completion of the child.

It may be desired that those who execute the command or shell script is himself not a child shell. This is accomplished by using the command “.” point.

Deutsch Romantisch ! !

Deja un comentario

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de

Estás comentando usando tu cuenta de Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s