Vous êtes sur la page 1sur 18

9.

1 Introduccin En este captulo, vamos a discutir cmo las herramientas


que has aprendido hasta ahora se pueden convertir en los scripts
reutilizables
9.2 Linux Fundamentos Objetivos del examen En este captulo se har cargo
de los temas de los siguientes objetivos del examen Linux Essentials: Tema
3: El Poder de la lnea de comandos (peso: 10) 3.3: Volviendo comandos en
un script Peso: 4 Descripcin: Turning comandos repetitivos en guiones
simples. Principales reas de Conocimiento: edicin de texto bsico
scripting Bsico shell La siguiente es una lista parcial de los usados
archivos, trminos y utilidades: / bin / sh Variables Argumentos para
los bucles eco Estado de la salida Las cosas que son bueno saber: pico,
nano, vi (slo lo bsico para la creacin de secuencias de comandos) Bash
Si mientras, declaraciones de caso leer y prueba, y [comandos

9.2 Linux Essentials Exam Objectives


This chapter will cover the topics for the following Linux Essentials exam objectives:
Topic 3: The Power of the Command Line (weight: 10)

3.3: Turning Commands into a Script

Weight: 4

Description: Turning repetitive commands into simple scripts.

Key Knowledge Areas:

Basic text editing

Basic shell scripting

The following is a partial list of the used files, terms, and utilities:

/bin/sh

Variables

Arguments

for loops

echo

Exit status

Things that are nice to know:

pico, nano, vi (only basics for creating scripts)

Bash

if, while, case statements

read and test, and [ commands

9.3 Scripts de Shell en una cscara de nuezUn script de shell es un


archivo de comandos ejecutables que se han almacenado en un
archivo de texto. Cuando se ejecuta el archivo, se ejecuta cada
comando. Shell scripts tienen acceso a todos los comandos de la
shell, incluyendo la lgica. Por tanto, un script puede detectar la
presencia de un archivo o buscar salida particular y cambiar su
comportamiento en consecuencia. Usted puede construir scripts para
automatizar partes repetitivas de su trabajo, lo que libera su tiempo y
garantiza la coherencia cada vez que utilice el guin. Por ejemplo, si
ejecuta los mismos cinco comandos de todos los das, puede
convertirlos en un script de shell que reduce su trabajo a un
comando.Un script puede ser tan simple como un comando
:echo "Hola, mundo!"
El guin, test.sh, consta de una sola lnea que imprime la cadena
"Hola, mundo!" A la consola.Ejecucin de una secuencia de comandos
se puede hacer ya sea pasndolo como argumento para la shell o
ejecutando directamente
bob: tmp $ sh test.sh
Hola mundo
!bob: tmp $ ./test.sh
-bash: ./test.sh : Permiso denegado
bob: tmp $ chmod + x ./test.sh
bob: tmp $ ./test.sh
Hola mundo

En el ejemplo anterior, en primer lugar, la secuencia de comandos se


ejecuta como un argumento a la cscara. A continuacin, el script se
ejecuta directamente desde el shell. Es raro tener el directorio actual
en la ruta de bsqueda binaria ($ PATH) por lo que el nombre tiene el
prefijo "./" para indicar que se debe ejecutar desde el directorio
actual.El error "Permiso denegado" significa que el guin no se ha
marcado como ejecutable. Un chmod rpida despus y el guin
funciona. chmod se usa para cambiar los permisos de un archivo, que
se explicar en detalle en un captulo posterior.Hay varias conchas
con su propia sintaxis del lenguaje. Por lo tanto, los scripts ms
complicados indicarn una concha en particular, especificando la ruta
absoluta al intrprete como la primera lnea, con el prefijo, como se
muestra "#!":
#! / bin / sh
echo "Hola, mundo!"
o
#! / bin / bash
echo "Hola, mundo!"
Los dos personajes, "#!" Tradicionalmente se llaman el hash y la
explosin, respectivamente, lo que conduce a la forma abreviada de
"tinglado" cuando se usan al comienzo de una secuencia de
comandos.Por cierto, el tinglado (o CrunchBang) se utiliza para scripts
de shell tradicionales y otros idiomas basados en texto como Perl,
Ruby y Python. Cualquier archivo de texto marcado como ejecutable
se ejecutar bajo el intrprete especificado en la primera lnea,
siempre y cuando el script se ejecuta directamente. Si el script se
invoca directamente como un argumento para un intrprete, como
secuencia de comandos sh o script bash, la cscara dada ser
utilizado no importa lo que est en la lnea de tinglado.Ayuda a
sentirse cmodos usando un editor de texto antes de escribir scripts
de shell, ya que lo necesitar para crear archivos de texto plano.
Herramientas de oficina tradicionales como LibreOffice que los
formatos de archivo de salida que contiene el formato y otros datos
no son apropiados para esta tarea

9.3 Shell Scripts in a Nutshell


A shell script is a file of executable commands that has been stored in a text file. When the
file is run, each command is executed. Shell scripts have access to all the commands of the
shell, including logic. A script can therefore test for the presence of a file or look for
particular output and change its behavior accordingly. You can build scripts to automate
repetitive parts of your work, which frees your time and ensures consistency each time you

use the script. For instance, if you run the same five commands every day, you can turn
them into a shell script that reduces your work to one command.
A script can be as simple as one command:
echo Hello, World!

The script, test.sh, consists of just one line that prints the string Hello, World! to the
console.
Running a script can be done either by passing it as an argument to your shell or by
running it directly:
bob:tmp $ sh test.sh
Hello, World!
bob:tmp $ ./test.sh
-bash: ./test.sh: Permission denied
bob:tmp $ chmod +x ./test.sh
bob:tmp $ ./test.sh
Hello, World

In the example above, first, the script is run as an argument to the shell. Next, the script is
run directly from the shell. It is rare to have the current directory in the binary search path
($PATH) so the name is prefixed with ./ to indicate it should be run out of the current
directory.
The error Permission denied means that the script has not been marked as executable. A
quick chmod later and the script works. chmod is used to change the permissions of a file,
which will be explained in detail in a later chapter.
There are various shells with their own language syntax. Therefore, more complicated
scripts will indicate a particular shell by specifying the absolute path to the interpreter as the
first line, prefixed by #! as shown:
#!/bin/sh
echo Hello, World!

or
#!/bin/bash
echo Hello, World!

The two characters, #! are traditionally called the hash and the bang respectively, which
leads to the shortened form of shebang when theyre used at the beginning of a script.
Incidentally, the shebang (or crunchbang) is used for traditional shell scripts and other textbased languages like Perl, Ruby, and Python. Any text file marked as executable will be run

under the interpreter specified in the first line as long as the script is run directly. If the script
is invoked directly as an argument to an interpreter, such as sh script or bash script,
the given shell will be used no matter whats in the shebang line.
It helps to become comfortable using a text editor before writing shell scripts, since you will
need to create files in plain text. Traditional office tools like LibreOffice that output file
formats containing formatting and other information are not appropriate for this task

9.4 Secuencias de comandos de edicin de Shell


UNIX tiene muchos editores de texto, los mritos de uno sobre el otro son a
menudo objeto de acalorados debates. Dos se mencionan especficamente en
el plan de estudios LPI Fundamentos: El editor nano GNU es un editor muy
simple muy adecuado para la edicin de pequeos archivos de texto. El Editor
de Visual, vi, o su versin ms reciente, VI mejoraron (vim), es un editor muy
potente, pero tiene una curva de aprendizaje empinada. Nos centraremos en
nano.
Escriba test.sh nano y ver una pantalla similar a esta:
Type nano test.sh and youll see a screen similar to this:

Nano has few features

Nano tiene algunas caractersticas para ponerse en su camino. Simplemente


escriba con el teclado, con las teclas de flecha para moverse y el botn de
borrar / retroceso para borrar el texto. A lo largo de la parte inferior de la
pantalla se puede ver algunos comandos disponibles para usted, que son
sensibles al contexto y cambian dependiendo de lo que ests haciendo. Si
usted est directamente en la mquina Linux en s, a diferencia de la conexin
en la red, tambin puede utilizar el ratn para mover el cursor y resaltar texto.
Para familiarizarse con el editor, comience a escribir un simple script de shell
mientras nano en el interior:

Note that the bottom

Tenga en cuenta que la opcin de la parte inferior izquierda es ^ X Salir que


significa "control de la prensa y X para salir". Presione Ctrl y X juntos y la parte
inferior cambiarn

Note that the bottom-left option is ^X Exit which means press control and X to exit. Press
Ctrl and X together and the bottom will change
bottom will change:

At this point, you can exit the program without

En este punto, se puede salir del programa sin guardar pulsando la tecla N, o
guardar primero pulsando Y para guardar. El valor predeterminado es guardar

el archivo con el nombre del archivo actual. Puede pulsar la tecla Intro para
guardar y salir.Usted estar de regreso en el intrprete de comandos despus
de guardar. Volver al editor. Esta vez presione Ctrl y O juntos para guardar su
trabajo sin salir del editor. Las indicaciones son en gran parte el mismo,
excepto que ests de vuelta en el editor.Esta vez, utilice las teclas de flecha
para mover el cursor a la lnea que tiene "El tiempo es". Pulse Control y K dos
veces para cortar las dos ltimas lneas en el bfer de copia. Mueva el cursor a
la lnea y pulse Control restante y U una vez para pegar el bfer de copia en la
posicin actual. Esto hace que la secuencia de comandos echo la hora actual
antes de saludar a usted y salv usted necesidad de volver a escribir las
lneas.Otros comandos tiles que pueda necesitar
son:ComandoDescripcinCtrl + W buscar el documentoCtrl + W, a continuacin
Control + R de bsqueda y reemplazoCtrl + G muestran todos los comandos
posiblesCtrl + Y la pgina / V hacia arriba / abajoCtrl + C muestran la posicin
actual en el archivo y el tamao del archivo
Ctrl + W search the document
Ctrl + W, then Control + R search and replace
Ctrl + G show all the commands possible
Ctrl + Y/V page up / down
Ctrl + C show the current position in the file and the files size
9.5 Conceptos bsicos de Scripting Tienes tu primera experiencia de scripting
anteriormente en este captulo, donde se introdujo un guin muy bsico que
corri un solo comando. El guin comenz con la lnea shebang, diciendo que
Linux / bin / bash (que es Bash) se va a utilizar para ejecutar el script. Aparte de
la ejecucin de comandos, hay 3 temas que debe familiarizarse con:
Variables, que contienen informacin temporal en el guin
Condicionales, que le permiten hacer cosas diferentes sobre la base de
pruebas que escribes
Bucles, que le permiten hacer la misma cosa una y otra vez
9.5.1 VariablesLas variables son una parte clave de cualquier lenguaje de
programacin. Aqu se muestra un uso muy sencilla de variables:#! / bin /
bashANIMAL = "pingino"echo "Mi animal favorito es un $ ANIMAL"Despus de
la lnea shebang es una directiva para asignar un texto a una variable. El
nombre de la variable es animal y el signo igual asigna la cadena "pingino".
Piense en una variable como una caja en la que puede almacenar cosas.
Despus de ejecutar esta lnea, el cuadro llamado "ANIMAL" contiene la
palabra "pingino".Es importante que no haya espacios entre el nombre de la
variable, el signo igual, y el artculo que se asignar a la variable. Si usted tiene
un espacio all, obtendr un error extrao como "command not found".
Aprovechando el nombre de la variable no es necesario, pero es una
convencin til para separar las variables de comandos a ejecutar.A
continuacin, la secuencia de comandos echos una cadena a la consola. La
cadena contiene el nombre de la variable precedida de un signo de dlar.
Cuando el intrprete ve que el signo de dlar reconoce que ser sustituyendo
el contenido de la variable, que se llama interpolacin. La salida del script es
luego "Mi animal favorito es un pingino".As que recuerde esto: Para asignar a
una variable, slo tiene que utilizar el nombre de la variable. Para acceder al
contenido de la variable, el prefijo con un signo de dlar. Aqu, se muestra una

variable se le asigna el contenido de otra variable!#! / bin / bashANIMAL =


pinginoALGO = $ ANIMALecho "Mi animal favorito es un $ ALGO"ANIMAL
contiene la cadena "pingino" (ya que no hay espacios, se muestra la sintaxis
alternativa sin utilizar comillas). ALGO est asignado a continuacin el
contenido del ANIMAL (porque ANIMAL tiene el signo de dlar en frente de
ella).Si usted quisiera, podra asignar una cadena interpolado a una variable.
Esto es bastante comn en los scripts de mayor tamao, como se puede
construir una orden ms grande y ejecutarlo!Otra manera de asignar a una
variable es utilizar la salida de otro comando como el contenido de la variable
encerrando el comando en las garrapatas de espalda:#! / bin /
bashCURRENT_DIRECTORY = `pwd`echo "Usted est en $
CURRENT_DIRECTORY"Este patrn se utiliza a menudo para procesar texto.
Usted puede tomar el texto de una variable o de un archivo de entrada y pasar
a travs de otro comando como sed o awk para extraer ciertas partes y
mantener el resultado en una variable.Es posible obtener la entrada del usuario
de su script y asignarlo a una variable a travs del comando de lectura:#! / bin /
bashecho -n "Cul es su nombre?"leer NOMBREecho "Hola $ NOMBRE!"Leer
puede aceptar una cadena desde el teclado o como parte del comando de
redireccin como usted aprendi en el ltimo captulo.Hay algunas variables
especiales, adems de los que usted ha establecido. Puede pasar argumentos
a la secuencia de comandos:#! / bin / bashecho "Hola $ 1"Un signo de dlar
seguido de un nmero N se corresponde con el argumento ensima pasado al
guin. Si llama el ejemplo anterior con ./test.sh la salida ser "Hola Linux". La
variable $ 0 contiene el nombre de la secuencia de comandos en s.Despus
de un programa se ejecuta, ya sea un binario o un script, devuelve un cdigo
de salida que es un nmero entero entre 0 y 255. Puede probar esto a travs
de la $? variable para ver si el comando anterior se complet con xito.bob:
tmp raz -q $ grep / etc / passwdbob: $ tmp echo $?0bob: tmp $ grep -q
Slartibartfast / etc / passwdbob: $ tmp echo $?1El comando grep se utiliza para
buscar una cadena dentro de un archivo con la bandera -q, que significa
"tranquila". Grep, mientras se ejecuta en modo silencioso, devuelve 0 si se
encuentra la cadena y 1 de otra manera. Esta informacin se puede utilizar en
un condicional para realizar una accin basado en la salida de otro
comando.Del mismo modo se puede establecer el cdigo de salida de su
propia secuencia de comandos con el comando exit:#! / bin / bash# Algo malo
sucedi!salida 1El ejemplo anterior muestra un comentario (#). Cualquier cosa
despus de la almohadilla se ignora que puede ser utilizado para ayudar a las
notas de licencia programador. La "salida 1" devuelve el cdigo de salida 1 a la
persona que llama. Esto funciona incluso en la cscara, si ejecuta este script
desde la lnea de comandos y escriba "$ echo?" Ver devuelve 1.Por
convencin, un cdigo de salida de 0 significa "todo est bien". Los cdigos de
salida mayor que 0 significa algn tipo de error que ocurri, que es especfico
para el programa. Por encima viste que grep utiliza 1 en el sentido de la cadena
no fue encontrado

9.5.1 Variables

Variables are a key part of any programming language. A very simple use of variables is
shown here:
#!/bin/bash

ANIMAL="penguin"
echo "My favorite animal is a $ANIMAL"

After the shebang line is a directive to assign some text to a variable. The variable name is
ANIMAL and the equals sign assigns the string penguin. Think of a variable like a box in
which you can store things. After executing this line, the box called ANIMAL contains the
word penguin.
It is important that there are no spaces between the name of the variable, the equals sign,
and the item to be assigned to the variable. If you have a space there, you will get an odd
error such as command not found. Capitalizing the name of the variable is not necessary
but it is a useful convention to separate variables from commands to be executed.
Next, the script echos a string to the console. The string contains the name of the variable
preceded by a dollar sign. When the interpreter sees that dollar sign it recognizes that it will
be substituting the contents of the variable, which is called interpolation. The output of the
script is then My favorite animal is a penguin.
So remember this: To assign to a variable, just use the name of the variable. To access the
contents of the variable, prefix it with a dollar sign. Here, we show a variable being
assigned the contents of another variable!
#!/bin/bash

ANIMAL=penguin
SOMETHING=$ANIMAL
echo "My favorite animal is a $SOMETHING"

ANIMAL contains the string penguin (as there are no spaces, the alternative syntax
without using quotes is shown). SOMETHING is then assigned the contents of ANIMAL
(because ANIMAL has the dollar sign in front of it).
If you wanted, you could assign an interpolated string to a variable. This is quite common in
larger scripts, as you can build up a larger command and execute it!
Another way to assign to a variable is to use the output of another command as the
contents of the variable by enclosing the command in back ticks:
#!/bin/bash
CURRENT_DIRECTORY=`pwd`
echo "You are in $CURRENT_DIRECTORY"

This pattern is often used to process text. You might take text from one variable or an input
file and pass it through another command like sed or awk to extract certain parts and keep
the result in a variable.
It is possible to get input from the user of your script and assign it to a variable through the
read command:
#!/bin/bash

echo -n "What is your name? "


read NAME
echo "Hello $NAME!"

Read can accept a string right from the keyboard or as part of command redirection like you
learned in the last chapter.
There are some special variables in addition to the ones you set. You can pass arguments
to your script:
#!/bin/bash
echo "Hello $1"

A dollar sign followed by a number N corresponds to the Nth argument passed to the script.
If you call the example above with ./test.sh the output will be Hello Linux. The $0
variable contains the name of the script itself.
After a program runs, be it a binary or a script, it returns an exit code which is an integer
between 0 and 255. You can test this through the $? variable to see if the previous
command completed successfully.
bob:tmp $ grep -q root /etc/passwd
bob:tmp $ echo $?
0
bob:tmp $ grep -q slartibartfast /etc/passwd
bob:tmp $ echo $?
1

The grep command was used to look for a string within a file with the q flag, which means
quiet. Grep, while running in quiet mode, returns 0 if the string was found and 1 otherwise.
This information can be used in a conditional to perform an action based on the output of
another command.
Likewise you can set the exit code of your own script with the exit command:
#!/bin/bash
# Something bad happened!

exit 1

The example above shows a comment (#). Anything after the hash mark is ignored which
can be used to help the programmer leave notes. The exit 1 returns exit code 1 to the
caller. This even works in the shell, if you run this script from the command line and then
type echo $? you will see it returns 1.
By convention, an exit code of 0 means everything is OK. Exit codes greater than 0 mean
some kind of error happened, which is specific to the program. Above you saw that grep
uses 1 to mean the string was not found

9.5.2 CondicionalesAhora que usted puede ver y establecer las variables, es el


momento de hacer su guin do diferentes funciones basadas en pruebas,
llamada ramificacin. La sentencia if es el operador de base para implementar
ramificacin.Un bsico si la declaracin es la siguiente:si algncomando;
despus # Hacer esto si algncomando tiene un cdigo de salida de 0fiEl
siguiente ejemplo se ejecutar "algncomando" (en realidad, todo hasta el
punto y coma) y si el cdigo de salida es 0 entonces el contenido hasta que se
llevar a cabo el cierre "ficcin". Usando lo que sabes sobre grep, ahora se
puede escribir un script que hace cosas diferentes en funcin de la presencia
de una cadena en el archivo de contraseas:#! / bin / bashsi grep -q root / etc /
passwd; despus raz de eco se encuentra en el archivo de contraseasotro
raz de eco no se encuentra en el archivo de contraseasfiA partir de los
ejemplos anteriores, es posible que recuerde que el cdigo de salida de grep
es 0 si no se encuentra la cadena. El ejemplo anterior utiliza esto en una lnea
a imprimir un mensaje si raz est en la contrasea o un mensaje diferente si
no lo es. La diferencia aqu es que en lugar de una "ficcin" para cerrar el
bloque if, hay una "cosa". Esto le permite realizar una accin si la condicin es
verdadera, y otro si la condicin es falsa. El bloque else todava debe estar
cerrada con la palabra clave fi.Otras tareas comunes son para buscar la
presencia de un archivo o directorio y para comparar cadenas y nmeros. Es
posible inicializar un archivo de registro si no existe, o comparar el nmero de
lneas en un archivo de la ltima vez que ejecut. "Si" es claramente el
mandato de ayudar aqu, pero qu comando usas para hacer la comparacin?
El comando de prueba le permite acceder fcilmente a los operadores de
comparacin y prueba de archivos. Por ejemplo:ComandoDescripcinprobar -f /
dev / ttyS0 0 si existe el archivoprueba! -f / Dev / ttyS0 0 si el archivo no existe/
si existe el directorio tmp 0 -d prueba-x prueba `que ls` sustituir la ubicacin de
ls luego probar si el usuario puede ejecutarprueba 1 -eq 1 0 si tiene xito
comparacin numricaprueba! 1 -eq 1 NO - 0 si la comparacin fallaprueba 1
-ne 1 Ms fcil, prueba de la desigualdad numricaprueba "a" = "a" 0 si la
comparacin de cadenas tiene xitoprueba "a"! = "a" 0 si las cadenas son
diferentesprueba 1 -eq 1 -o 2 -eq 2 -o es OR: o bien puede ser el mismoprueba
1 -eq 1 -a 2 -eq 2 -a es Y: ambos deben ser los mismosEs importante sealar
que la prueba se ve en enteros y de cadena comparaciones diferente. 01 y 1
son los mismos por comparacin numrica, pero no por comparacin de
cadenas. Siempre hay que tener cuidado de recordar qu tipo de entrada que
usted espera.Hay muchas ms pruebas, como -gt por mayor que, la manera de
probar si un archivo es ms reciente que el otro, y muchos ms. Consulte la

pgina de manual de prueba para ms.la prueba es bastante detallado para un


comando que se usa con tanta frecuencia, por lo que es un alias para que
llam '[' (corchete izquierdo). Si encierra sus condiciones entre corchetes, es lo
mismo que ejecutar la prueba. Por lo tanto, estas declaraciones son idnticas.si
-f test / tmp / foo; despusif [-f / tmp / foo]; despusSi bien es la ms utilizada
esta ltima forma, es importante entender que el corchete es un comando en
su propia que opera de manera similar a la prueba excepto que requiere el
corchete de cierre."Si" tiene una forma final, que te permite hacer
comparaciones mltiples a la vez utilizando "elif" (abreviatura de else if).#! /
bin / bashif ["$ 1" = "hola"]; despus echo "hola a ti mismo"elif ["$ 1" = "adis"];
despus echo "agradable de haberte conocido" echo "Espero volver a
verte"otro echo "yo no entenda que"fiEl cdigo anterior se compara el primer
argumento pasado al guin. Si es hola, se ejecuta el primer bloque. Si no es
as, el script comprueba si es adis y echos un mensaje diferente en tal caso.
De lo contrario, se enva un tercer mensaje. Tenga en cuenta que la variable $
1 es citado y el operador de comparacin de cadenas se utiliza en lugar de la
versin numrica (eq).Los if / elif / pruebas ms puede llegar a ser bastante
prolija y complicada. La declaracin de caso ofrece una forma diferente de
hacer mltiples pruebas ms fcil.#! / bin / bashcase "$ 1"hola | hi) echo "hola
a ti mismo" ;;Adis) echo "agradable de haberte conocido" echo "Espero
volver a verte" ;;*) echo "yo no entenda que"esacLa declaracin de caso
comienza con una descripcin de la expresin est probando: Caso de
expresin en la expresin aqu es el cotizado $ 1..A continuacin, cada
conjunto de pruebas se ejecutan como una coincidencia de patrn terminado
por un parntesis de cierre. El ejemplo anterior se ve por primera vez para
"hola" o "hola"; mltiples opciones estn separadas por la barra vertical (|), que
es un operador OR en muchos lenguajes de programacin. A continuacin que
son los comandos que se ejecutarn si el patrn devuelve verdadero, que se
terminan por dos puntos y comas. El patrn se repite.El patrn * es lo mismo
que una persona, ya que coincide con cualquier cosa. El comportamiento de la
declaracin de caso es similar al if / elif / else en que el procesamiento se
detiene despus de que el primer partido. Si ninguna de las otras opciones de
juego con el * asegura que el ltimo coincidir.Con una slida comprensin de
los condicionales usted puede tener sus guiones toman acciones slo si es
necesario

9.5.2 Conditionals
Now that you can look at and set variables, it is time to make your script do different
functions based on tests, called branching. The if statement is the basic operator to
implement branching.
A basic if statement looks like this:
if somecommand; then
# do this if somecommand has an exit code of 0
fi

The next example will run somecommand (actually, everything up to the semicolon) and if
the exit code is 0 then the contents up until the closing fi will be run. Using what you know
about grep, you can now write a script that does different things based on the presence of a
string in the password file:
#!/bin/bash

if grep -q root /etc/passwd; then


echo root is in the password file
else
echo root is missing from the password file
fi

From previous examples, you might remember that the exit code of grep is 0 if the string is
found. The example above uses this in one line to print a message if root is in the password
or a different message if it isnt. The difference here is that instead of an fi to close off the
if block, theres an else. This lets you do one action if the condition is true, and another if
the condition is false. The else block must still be closed with the fi keyword.
Other common tasks are to look for the presence of a file or directory and to compare
strings and numbers. You might initialize a log file if it doesnt exist, or compare the number
of lines in a file to the last time you ran it. If is clearly the command to help here, but what
command do you use to make the comparison?
The test command gives you easy access to comparison and file test operators. For
example:
Command

Description

test f /dev/ttyS0

0 if the file exists

test ! f /dev/ttyS0

0 if the file doesnt exist

test d /tmp

0 if the directory exists

test x `which ls`

substitute the location of ls then test if the user can execute

test 1 eq 1

0 if numeric comparison succeeds

test ! 1 eq 1

NOT 0 if the comparison fails

test 1 ne 1

Easier, test for numeric inequality

test a = a

0 if the string comparison succeeds

test a != a

0 if the strings are different

Command

Description

test 1 eq 1 o 2 eq 2

-o is OR: either can be the same

test 1 eq 1 a 2 eq 2

-a is AND: both must be the same

It is important to note that test looks at integer and string comparisons differently. 01 and 1
are the same by numeric comparison, but not by string comparison. You must always be
careful to remember what kind of input you expect.
There are many more tests, such as gt for greater than, ways to test if one file is newer
than the other, and many more. Consult the test man page for more.
test is fairly verbose for a command that gets used so frequently, so there is an alias for it

called [ (left square bracket). If you enclose your conditions in square brackets, its the
same as running test. So, these statements are identical.
if test f /tmp/foo; then
if [ -f /tmp/foo]; then

While the latter form is most often used, it is important to understand that the square
bracket is a command on its own that operates similarly to test except that it requires the
closing square bracket.
if has a final form, that lets you do multiple comparisons at one time using elif (short for
else if).
#!/bin/bash

if [ "$1" = "hello" ]; then


echo "hello yourself"
elif [ "$1" = "goodbye" ]; then
echo "nice to have met you"
echo "I hope to see you again"
else
echo "I didn't understand that"
fi

The code above compares the first argument passed to the script. If it is hello, the first
block is executed. If not, the script checks to see if it is goodbye and echos a different
message if so. Otherwise, a third message is sent. Note that the $1 variable is quoted and
the string comparison operator is used instead of the numeric version (-eq).

The if/elif/else tests can become quite verbose and complicated. The case statement
provides a different way of making multiple tests easier.
#!/bin/bash

case "$1" in
hello|hi)
echo "hello yourself"
;;
goodbye)
echo "nice to have met you"
echo "I hope to see you again"
;;
*)
echo "I didn't understand that"
esac

The case statement starts off with a description of the expression being tested: case
EXPRESSION in. The expression here is the quoted $1.
Next, each set of tests are executed as a pattern match terminated by a closing
parenthesis. The previous example first looks for hello or hi; multiple options are
separated by the vertical bar (|) which is an OR operator in many programming languages.
Following that are the commands to be executed if the pattern returns true, which are
terminated by two semicolons. The pattern repeats.
The * pattern is the same as an else because it matches anything. The behavior of the case
statement is similar to the if/elif/else statement in that processing stops after the first match.
If none of the other options matched the * ensures that the last one will match.
With a solid understanding of conditionals you can have your scripts take actions only if
necessary.

9.5.3 LoopsLoops permiten cdigo que se ejecuta repetidamente. Pueden ser


de utilidad en numerosas situaciones, como cuando se desea ejecutar los
mismos comandos ms de cada archivo en un directorio, o repetir alguna
accin 100 veces. Hay dos bucles principales en scripts de shell: el de bucle y
el bucle while.Para bucles se utiliza cuando se tiene una coleccin finita sobre
el que desea repetir, como una lista de archivos, o una lista de nombres de
servidor:#! / bin / bashSERVIDORES = "servera ServidorB ServidorC"para S en
$ SERVIDORES; hacer echo "Hacer algo a $ S"hechoEl script establece
primero una variable que contiene una lista separada por espacios de nombres
de servidores. La sentencia for continuacin bucles sobre la lista de servidores,
cada vez que cambia la variable S al nombre del servidor actual. La eleccin de
S fue arbitraria, pero tenga en cuenta que la S no tiene signo del dlar, pero los

$ SERVIDORES hace, mostrando que $ SERVIDORES se ampliarn a la lista


de servidores. La lista no tiene por qu ser una variable. Este ejemplo muestra
dos maneras ms para aprobar una lista.#! / bin / bashpara NAME en Sean Jon
Isaac David; hacer echo "Hola $ NOMBRE"hechopara S en *; hacer echo
"Hacer algo a $ S"hechoEl primer bucle es funcionalmente el mismo que el
ejemplo anterior, excepto que la lista se pasa al bucle for directamente en lugar
de utilizar una variable. Usando una variable ayuda a la claridad de la escritura
como alguien puede hacer fcilmente los cambios a la variable en lugar de
mirar a un bucle.El segundo bucle utiliza un * que es un glob archivo. Esto se
expandi por el shell para todos los archivos en el directorio actual.El otro tipo
de lazo, un bucle while, opera en una lista de tamao desconocido. Su trabajo
es mantener en marcha y en cada iteracin realizar una prueba para ver si
debe ejecutar otra vez. Usted puede pensar en l como "mientras que algunos
condicin es verdadera, hacer cosas."#! / bin / bashi = 0mientras que [$ i -LT
10]; hacer echo $ i i = $ (($ i + 1))hechoecho "Se ha terminado de contar"El
ejemplo anterior muestra un bucle while que cuenta de 0 a 9. Una variable de
contador, i, se inicializa a 0. A continuacin, un bucle while se ejecuta con ser la
prueba "es $ i menos de 10?" Tenga en cuenta que los usos bucle while la
misma notacin que una sentencia if!Dentro del bucle mientras que el valor
actual de i se hizo eco y luego 1 se aade a la misma a travs del comando $
((aritmtica)) y se asigna de nuevo en i. Una vez que se convierte en el 10 de la
sentencia while devuelve false y el proceso contina despus del bucle

9.5.3 Loops
Loops allow code to be executed repeatedly. They can be useful in numerous situations,
such as when you want to run the same commands over each file in a directory, or repeat
some action 100 times. There are two main loops in shell scripts: the for loop and the while
loop.
For loops are used when you have a finite collection over which you want to iterate, such as
a list of files, or a list of server names:
#!/bin/bash

SERVERS="servera serverb serverc"


for S in $SERVERS; do
echo "Doing something to $S"
done

The script first sets a variable containing a space separated list of server names. The for
statement then loops over the list of servers, each time it sets the S variable to the current
server name. The choice of S was arbitrary, but note that the S has no dollar sign but the
$SERVERS does, showing that $SERVERS will be expanded to the list of servers. The list
does not have to be a variable. This example shows two more ways to pass a list.

#!/bin/bash

for NAME in Sean Jon Isaac David; do


echo "Hello $NAME"
done

for S in *; do
echo "Doing something to $S"
done

The first loop is functionally the same as the previous example, except that the list is
passed to the for loop directly instead of using a variable. Using a variable helps the clarity
of the script as someone can easily make changes to the variable rather than looking at a
loop.
The second loop uses a * which is a file glob. This gets expanded by the shell to all the files
in the current directory.
The other type of loop, a while loop, operates on a list of unknown size. Its job is to keep
running and on each iteration perform a test to see if it should run another time. You can
think of it as while some condition is true, do stuff.
#!/bin/bash

i=0
while [ $i -lt 10 ]; do
echo $i
i=$(( $i + 1))
done
echo Done counting

The example above shows a while loop that counts from 0 to 9. A counter variable, i, is
initialized to 0. Then a while loop is run with the test being is $i less than 10? Note that the
while loop uses the same notation as an if statement!
Within the while loop the current value of i is echoed and then 1 is added to it through the $
(( arithmetic )) command and assigned back into i. Once i becomes 10 the while statement
returns false and processing continues after the loop.

Vous aimerez peut-être aussi