Abrir el menú de navegación
Cerrar sugerencias
Buscar
Buscar
es
Change Language
Cambiar idioma
Cargar
Iniciar sesión
Iniciar sesión
Descargar gratis durante días
0 calificaciones
0% encontró este documento útil (0 votos)
210 vistas
Programacion Shell en UnixLinux PDF
Cargado por
Arturo Macias Mazari
Título mejorado con IA
Derechos de autor
© © All Rights Reserved
Formatos disponibles
Descarga como PDF o lee en línea desde Scribd
Descargar ahora
Descargar
Guardar Programacion Shell en UnixLinux.pdf para más tarde
Descargar
Guardar
Guardar Programacion Shell en UnixLinux.pdf para más tarde
0%
0% encontró este documento útil, undefined
0%
, undefined
Insertar
Compartir
Imprimir
Reportar
0 calificaciones
0% encontró este documento útil (0 votos)
210 vistas
Programacion Shell en UnixLinux PDF
Cargado por
Arturo Macias Mazari
Título mejorado con IA
Derechos de autor
© © All Rights Reserved
Formatos disponibles
Descarga como PDF o lee en línea desde Scribd
Descargar ahora
Descargar
Guardar Programacion Shell en UnixLinux.pdf para más tarde
Carrusel anterior
Carrusel siguiente
Guardar
Guardar Programacion Shell en UnixLinux.pdf para más tarde
0%
0% encontró este documento útil, undefined
0%
, undefined
Insertar
Compartir
Imprimir
Reportar
Descargar ahora
Descargar
Está en la página 1
/ 353
Buscar
pantalla completa
Recursos Informatics Programacion shell en Unix/Linux sh, ksh, bash Patt om Christine DEFFAIX REMY. Hizey wae nae ceryTodas las marcas citadas han sido registradas por su respectivo editor. Reservados todos los derechos. El contenido de esta obra est protegido por la ley, que establece penas de prisién y/o multas, ademds de las correspondientes indemnizaciones por dafios y perjuicios, para quienes reprodujeren, plagiaren, distribuyeren o comunica- ren publicamente, en todo o en parte, una obra literaria, artistica o cientifica, o su trans- formacién, interpretacién o ejecucién artistica fijada en cualquier tipo de soporte o comunicada a través de cualquier medio, sin la preceptiva autorizacién. Copyright - Editions ENI - Octubre 2012 ISBN: 978-2-7460-7623-5 Edicién original: 978-2-7460-6714-1 Ediciones ENI es una marca comercial registrada de Ediciones Software. Ediciones ENI P° Ferrocarriles Catalanes, 97-117, 2a pl. of. 18 08940 - Cornella de Llobregat (Barcelona) Tel: 934 246 401 Fax: 934 231 576 e-mail:
[email protected]
http://www.ediciones-eni.com Autor: Christine DEFFAIX REMY, Edicién espafiola: Arnau ONCINS RODRIGUEZ Coleccién Recursos Informaticos dirigida por Joélle MUSSETContenido Podré descargar algunos elementos de este libro en Ia pagina web de Ediciones ENI: http://www.ediciones-eni.com. Escriba la referencia ENI del libro RIT3PRO en la zona de busqueda y valide, Haga clic en el titulo y después en el bot6n de descarga. Prélogo Capitulo 1 Introduccién ._Caracterfsticas de un intérprete de comandos ........... 0.00.05 . Historia de Shell |. Principales intérpretes de comandos aR WIN ). Shells tratados en este libro.......... Capitulo 2 1._Comandos internos y externos 1.1_Comandos externos 19 1.2 Comandos internos : : 13 Implementacién interna e implementaci6n externa ......... 2. _Impresi6n por pantalla. .......0eeeeeee eee eee eee 2.1 El comando echo. E ir "\n" 2.1.2 El cardcter" 2.1.3 El car4cter "\t" 2.1.4 Listado de caracteres de escape 2.2 Los comandos print y printf 3. El cardcter ~ (tilde)2—_Programacién Shell en Unix/Linux sh, ksh, bash 4. Elcomando interno cd... 5.1 5.3 6. Separador de comandos . 7. Redirecciones 7A 2_Herencia Expresiones basicas. 5.1.1 El caracter *. 5.1.2 EH cardcter ? 5.1.3 Los caracteres [ ] pani Expresiones complejas........... 5.2.1 Yexpresion).. 5.2.2 *(expresién) . 5.2.3 +(expresi6n). 5.2.4 @(expresion). 5.2.5 \(expresi6n) 5.2.6 Alternativas. . Interpretacién del shell. Entrada y salidas estandar de los procesos . 7.1.1 Entrada estandar Redireccién de las salidas en escritura. 7.3.1 Salida estandar 7.3.2 Salida de error estandar 7.3.3 Salida estaéndar y salida de error estandar . 39 7.3.4 Eliminar las impresiones por pantalla 7.3.5 Mecanismo interno . Redireccion de la entrada estandar . Redirecciones avanzadas 7.5.1. Reditigir los descriptores 1 y 2 hacia el mismo archivo ..43 7.5.2 La redirecci6n doble en lectura . 7.5.3 Cierre de un descriptor.Contenido —__W[J[{___ 8.1 Comandos que no leen su entrada estdndar . 8.2 Comandos que leen su entrada esténdar. 8.2.1 Ejemplos triviales 8.2.2 Caso de los filtros 8.3 Complementos....... 0 cas B27 Encadénat tibetine 2 stb soem er OD, 8.3.2 Duplicar las salidas......00.cee0eeeseseeeeeeeseee 59 8.3.3 Enviar la salida estandar y la salida de error estandar por la tuberfa.. 9. Agrupacién de comandos. . 9.1 Paréntesis. . 9.2 Las llaves 9.3 Conclusion . . 10. Procesos en segundo plano. Capitulo 3 Configuracién del entorno de trabajo 4. SV aTADIES AE SATO recconcenconprpe a RTE RRNA RANON 73 jie Lista Wewariabless ss a a ere 1.2 Mostrar el valor de una variable senna: 1.3 Modificacién del valor de una variable . 74 14 Variables principales. 5 1.4.1 HOME. 1.4.2 PATH.. TATE 148 LOGNAME 834____Programacién Shell en Unix/Linux sh, ksh, bash . 83 83 1.5 Exportacién de variables 1.5.1 Listado de variables exportadas. 1.5.2 Variables que deben exportarse. 84 1.5.3 Exportar una variable......... 84 2. Las opciones del shell smaepa ase MTR RUEESETIA vane BB 2.1 Activar y desactivar una opcién del shell .. 2.2 Visualizar la lista de opciones 2.3 Opciones principales . 2.3.1 ignoreeo . 2.3.2. noclobber. . . 2.3.3 emacs vi. 32: Visuabzaria lista déalias cviocusas cae coma one 3.2.1 Visualizar todos los alias 3.2.2 Visualizar un alias en particular . . 4. Histérico de comando: 4.1 Configurar la recuperacion de comandosenksh .......... ALLL OPCGRvis .| sciveinenean ccletien «HR nenN. SENG 4.1.2 Opcién emacs 4.2. Configurar la recuperacién de comandos en bash . 4.3 Completar nombres de archivo... . 4.3.1 Completar en bash. ... 4.3.2 Completar en ksh... 5.1.2 Archivos de entorno lefdos por el shell de conexi6n. .. . 104 5.2 Sesi6n utilizando un Bourne Shell......... 0. 00000e 000s 107Contenido 4.2 Sesién utilizando un Korn Shell 108 5.4 Sesién utilizando un Bourne Again Shell .................111 Capitulo 4 . Las bases de la programacién shell 1. Las variables de usuario 113 1.1. Poner nombre a una variable 118 1.2. Definir una variable : 1.2.1 Asignar una cadena de caracteres a una variable ...114 1.2.2 Asignar una cadena de caracteres con al menos un espacio. 1.2.3 Variable indefinida ..... 1.2.4 Borrar la definicién de una variable. 1.2.5 Aislar el nombre de una variable . 1.3. Sustitucién de variables 3,_Caracteres de protecci6n ... . 3.1 Las comillas simples 3.2 Elcardcter\.. : 3 fae comillacdoblée ais Soe as pe Ay RECAPIEMEBH se ncanasians maraaneeen amas savbeewvanss AIS 5,_Interpretacién de una linea de comandos... 124 6._Escritura y ejecucién de un script en shell ..........11.s 11.126 6.1 Definicidn 6.2_Ejecuci6n de un script por un shell hijo ............s.0ss 6.3. Ejecucién de un script porel shell actual . 6.4 Comentarios 7. Variables reservadas del shell . . 7.1 Los parémetros posicionales. 7.2, Elcomando shift. 7.2.1 Sintaxisaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.Contenido 12. Sustitucién de expresiones aritméticas.......... 0.00 cece eee AZL 13. Correcci6n de un script .. TWh Opel kimans anes 13.2 Otras opciones . TALS Bet Eiasde cont ie sh ust set a ER 14.1 if L 14.2 CasCrsercquaay saypeIS RRR RERE BITTERLY BRIS, 14.2.1 Sintaxis ... 14.2.2 Principio 14.3 Bucle for .. 14.4 Bucle while 14.4.1 Sintaxis . 14.4.2 Uso... 14.4.3 Bucle infinito. . Capitulo 5 Aspectos avanzados de la programacién shell 1. Comparacién de las variables $* y $@ . 1.1 Uso de $* yee 1.2 Usode"$*" . 1.3. Uso de"$@" 2. Sustitucién de variables . F decmmaioenat 2.1 Longitud del valor contenido en una ‘variable : 207 2.2. Manipulacién de cadenas de caracteres. a +207 2.2.1 Bliminar el fragmento mds pequefio dela izquierda . ..208 2.2.2. Eliminar el fragmento mas grande de la izquierda ... ..208aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.Contenido 7.3 Tratamiento de un archivo . 285 73.1 Informacién previa . 285 7.3.2 Las diferentes formas de explotar un archivo. +236 7.3.3 Repartir una linea en campos . .. 6242 8. Elcomando eval . 9. Gestién de sefiales 9.1 Sefiales principales . 9.2 Ignorar una sefial . 9.3 Modificar el compattamients asociado auna sefial. 9.4 Restablecer el comportamiento por defecto del shell respecto a una sefial..... 9.5. Usar trap desde un script de shell . 10. Gestién de mentis con select 11. Anilisis de las opciones de un script con getopts 12, Gestion de un proceso en segundo plano .... 13. Script de archivado incrementaly transferencia sftp automitica .. 13.1 Objetivo. % 2 13.2 El archivo uploadBackup sh. 13.3 E] archivo funciones.inc.sh. . Capitulo 6 Expresiones regulares 1. Introduccién . Caracteres comunes en ERby ERe ... . 2. 3. Caracteres especfficos de ERb 4, . Caracteres espectficos de ERe.10___Programaci6n Shell en Unix/Linux sh, ksh, bash 5. Uso de expresiones regulares por comandos. 5.1 El comando vi. 5.2 Elcomando grep. 5.3. Ecomando expr. boone Le 5A sed y AWK. o.oo cece ccc ee cece eee eesveseeteeeteveee Capitulo 7 El comando sed 1. Uso del comando sed... ..0606e.c.00ceceeeeeeeeeeeeeeees By Bjemplonyn, sree, seve, stitian de delgermenieesss 2.1 Uso de sed en linea de comandos. ..... 2.1.1 El comando d (delete) 2.1.2 El comando p (print) 2.1.3 Elcomando w (write)... 0.0.00 cece ee vce cece ees 2.1.4 Negacién de un comando (!) 2.1.5 El comando s (sustituci6n) ....... 000-2... eee 2.2 Script sed Capitulo 8 El lenguaje de programacién awk 1. Principio . 1.1. Sintaxis . : 1.2 Variables especiales, 1.2.1 Variables predefinidas a partir de la ejecucién de awk. . 1.2.2 Variables inicializadas en el momento del tratamiento deta lineaxccanemgier es 1.2.3 Ejemplos simples .. 1.3. Griterios de selecci6n s vewes cia esas 1.3.1 Expresiones regulares . Verificaciones légicas 1.3.3 Intervalos de lineas............ ..279 287 -. 290 - 290 290 291 292 293 293 295 “304 «305 306Contenido Ans WN 10. 1.4 Estructura de un script awk. LAT BEGIN wcmmc eens se * 1.4.2 Secciones intermedias. . . 1.4.3 END. 1.4.4 Comentarios . 1.4.5 Variables . : 1.4.6 Ejemplo.. . 307 Operadores oe. eee eeeeeeteenees La funcién printf. ..... Redirecciones ............+-+5 . Lectura de la linea siguiente: next. . Estructuras de control ......... # 6.1 if.. 6.2 for 6.3 While.. 6.4 do-while. 6.5 break... 6.6 continue Finalizar un script............. Tablas 0.00... cee eee ee eee eee : 8.1 Tablas indexadas con un entero .... 8.2. Tablas asociativas. . 8.2.1 Definicién 3 8.2.2. Verificar Ia existencia de un elemento 8.2.3 Eliminar un elemento Los argumentos de la linea de comandos ..........200ee0ee0 es Funciones integradas . sees 10.1 Funciones que trabajan con cadenas. 10.2 Funciones matematicas . i12____Programacién Shell en Unix/Linux sh, ksh, bash 10.3 Otras funciones 326 10.3.1La funcién getline 326 11. Funciones de usuario .. . 10.3.21a funcién close ..... 0... 10.3.3La funcién system . - 330 . B31 » 832 12. Ejemplos de scripts. . or a s wee BA, 12.1 Anilisis de un archive de log sistaceesets o's B84 12.2 Generacién de un archivo de etiquetas » 336 Capitulo 9 Los comandos filtro 1. Introduccién . ae BR v 2. Sintaxis de waits a a filtco 8. Visualizacién de datos ........ 3.1 3.2 3.3 34 3.5 3.6 3.7 3.8 4, Tratamiento de datos. ~ 839 339 Consulta de datos, creacién. de achive: cat. Valor de los bytes de un flujo de dat id. Filtrado de Iineas: grep . . Ultimas lineas de un flujo de datos: tail Priniceas lniese'de ui Hujo de datos: head. Duplicacién de la salida esténdar: tee . Numeracién de Ifneas: nl....... Presentacién de un flujo de datos: pr .. Conteo de lineas, de palabras y caracteres: we. . Extracci6n de caracteres: cut . Ordenacién de datos: sort . paste senna SDE acncsienm amen Transformacién de caracteres: tr. : Eliminaci6n de lineas repetidas: uniq ..aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.Capitulo 1 Introduccién . Definicién del shell El shell es un programa que tiene como funci6n la de proporcionar Ja interfaz entre el usuario y el sistema Unix, Es un intérprete de comandos. Hay varios shells disponibles para las plataformas Unix. . Caracteristicas de un intérprete de comandos Los intérpretes de comandos disponibles en los entornos Unix tienen en comiin las siguientes funcionalidades: = Proponen un juego de caracteres especiales que permiten desencadenar acciones concretas. ~ Tienen comandos internos y palabras clave mediante algunos de los cuales se puede programar. — Utilizan archivos de inicializaci6n que permiten a un usuario parametrizar su entorno de trabajo. Cada shell propone sus propios caracteres especiales, comandos internos, palabras clave y archivos de configuraci6n. Afortunadamente, los intérpretes de comandos actualmente més utilizados derivan todos del shell Bourne y tienen, por consiguiente, un cierto numero de funcionalidades en comtn. 15aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.Capitulo 2 Mecanismos esenciales de! shell 1. Comandos internos y externos Este capitulo presenta y explica de manera detallada las funcionalidades basicas del shell comunmente utilizadas en los comandos Unix. Un comando Unix pertenece a una de las dos siguientes categorfas: 1.1 Comandos externos Un comando externo es un archivo localizado en el Arbol del sistema de archivos. Por ejemplo, cuando un usuario ejecuta el comando 1s, el shell pide al nucleo de Unix cargar en memoria el archivo /usr/bin/Is. Se consideran comandos externos los archivos que tengan uno de los formatos siguientes: ~ Archivos con formato binario ejecutable. — Archivos con formato de texto que representan un script de comandos (que puede estar escrito en Shell o en otro lenguaje, como por ejemplo Perl). El comando file indica el tipo de datos contenidos en un archivo. 19aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.Nn 2. 2.1. 23 Mecanismos esenciales del shell Capitulo 2 /home/cristina $ ed /usr/bin $ ./pwa /usr/bin $ Impresi6n por pantalla El comando echo El comando interno echo permite realizar impresiones por pantalla. Ejemplo $ echo 1He aqui un libro de programacién shell! iHe aqui un libro de programacién shell! $ Ciertos caracteres tienen un significado especial cuando se ponen entre comillas (apéstrofes o comillas dobles). Estos caracteres son los caracteres de escape. £l comando ecko de bash debe ser usado con fa opcidn -e para que se Tealice la interpretacién de los caracteres de escape. El cardcter "\n" Sirve para provocar un salto de linea. Elemplo con un shell diferente de bash $ echo "He aqui un salto de linea\ny otro\ny el salto de linea natural del comando echo" He aqui un salto de linea y otro y el salto de linea natural del comando echo $aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.s 27 Mecanismos esenciales del shell Capitulo 2 El comando intemo cd A continuacién presentamos las sintaxis particulares del comando ed. Ejemplos El comando ed sin argurnento permite al usuario volver a su directorio de inicio: Sed Lo mismo que utilizando el caracter ~ : ksh bash $ ed ~ Cambiar al directorio de inicio del usuario sebastian: ksh [bash $ pwd /home/cristina $ ed ~sebastian $ pwd /home/sebast ian Volver al directorio anterior con ed -: ksh = |bash S$ ca - /home/cristina Sustituci6n de nombres de archivos Numerosos comandos toman nombres de archivo como argumento. Estos ul- timos se pueden citar literalmente 0 se pueden especificar de forma més gené- rica. El shell propone un cierto nimero de caracteres especiales que permiten fabricar expresiones utilizadas como modelos de nombres de archivo.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.5.2.3 5.2.4 5.2.5 31 Mecanismos esenciales del shell Capitulo 2 +(expresién) La expresién estard presente entre 1 y n veces. Ejemplo Archivos cuyo nombre comience por "fic", seguido de al menos | occurren- cia de "866", seguido de "log": $ 1s fic+(866) .log ficB66.log ficesEBE6.1og FicB6ER6EBES. log @(expresién) La expresién estaré presente sdlo 1 vez. Ejemplo Archives cuyo nombre comience por "fic", seguido de exactamente una ocurrencia de "866", sequido de "log": $ 1s £ic@(866) .log £1c866.1og {(expresion) La expresiOn no estaré presente. Ejemplos Archives cuyo nombre comience por "fic", seguido de una expresién que no sea la cadena "866", seguido de "Jog": $ 1s fic! (866) .log fic.log £ic866866866.log fic867.1og fic866866.log £ic866868.1og £1ic868. log s Archivos cuyo nombre no empiece por "fic: $ 1s 1 (fic#) readme.txt typescript 8aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.35 Mecanismos esenciales del shell Capitulo 2 7.1.2 Salida esténdar Al descriptor de archivo 1 se le llama también Salida estandar del proceso. Por convenio, un proceso que desea enviar un mensaje de resultado al usuario tiene que hacerlo a través del descriptor 1. Si éste tiltimo esta asociado al ter- minal, que es como est4 por defecto, se materializa al usuario como una im- presién por pantalla. 7.1.3 Salida de error esténdar AI descriptor de archivo 2 se le llama también Salida de error estandar del proceso. For convenio, un proceso que desea enviar un mensaje de error al usuario tiene que hacerlo a través del descriptor 2. Si éste Gltimo estd asociado al terminal, que es como esta por defecto, se materializa al usuario como una impresi6n por pantalla. 7.2 Herencia Los descriptores de archivos son heredados en la duplicacién (fork()) y el reem- plazo (exec()). La figura 4 muestra que el shell ksh hijo, después del comando find hereda la tabla de descriptores de archivos del shell padre. Este comando envia por la salida estdndar los resultados y por la salida de error estandar la lista de directorios que el usuario no tiene permisos para explorar. Como las salidas 1 y 2 estan orientadas al mismo terminal, las impresiones en pantalla se entrelazan. Una de las caracterfsticas interesantes de las redirecciones es la de poder separar los mensajes procedentes de cada descriptor.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.39 Mecanismos esenciales del shell Capitulo 2 Ejemplo Concatenacién de los mensajes de error de 1s -z al final del archivo error: Sle -= 1s: illegal option -- z usage: 1s -1RaAdCxmnlogrtucpFbqisfl [files] § lg -z 2>> error $ cat error find: cannot read dir /lost+found: Permission denied find: cannot read dir /usr/aset: Permission denied As: illegal option -- z usage: 1s -1RaAdCxmnlogrtucpFbgis{L [files] s 7.3.3 Salida estandar y salida de error estandar Es posible redirigir multiples descriptores en una misma linea de comandos. $ comando 1> archivo_a 2> archivo b ° $ comando 2s archivo_b 1= archivo_a bservacion Las redirecciones son siempre tratadas de izquierda a derecha. En este caso, el orden de eseritura de las dos realiecciones no importa, pero no siempre serd asi (ver el punto Redirecciones - Redirecciones avanzadas). $ find / -name passwd 1> resu 2> error 3 cat resu /var/adn/passwa /usr/bin/passwa /etc/default /passwd /etc/passwa $ cat error find: cannot read dir /lost+found: Permission denied find: cannot read dir /usr/aset: Permission denied $aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.Mecanismos esenciales del shell Capitulo 2 43 2? etapa: El comando mail realiza una lectura del descriptor 0 PID=201 mail olivia 0| <¢4— /dew/pts/1 [<— mensaje 1 Pte saevsoesrt Toe Hevictsr. 2] ——¥ /dev/pts/1 2| —®» /dev/pts/1 Figura 8 Mecanismo interno de la redirecci6n en lectura - Segunda etapa 7.5 Redirecciones avanzadas 75. Redirigir los descriptores 1 y 2 hacia el mismo archivo Para enviar la salida estdndar y la salida de error estandar hacia el mismo archivo, es necesario emplear una sintaxis particular. A continuacién, se muestra lo que no hay que escribir y la raz6n por la que no funcionard. Sintaxis incorrectas $ comando 1> archivo 2> archivo $ comando 1> archivo 2>> archivo El problema no reside en el hecho de abrir dos veces el mismo archivo (es per- fectamente legal dentro del mismo proceso), sino en que hay un offset (posi- cién actual dentro del archivo) asociado a cada apertura. ;Cuéles son las consecuencias? — La secuencia de resultados en el archivo no ser forzosamente representativa del orden en el que se desarrollan los eventos. ~ Los resultados emitidos a través de los descriptores 1 y 2 corren el riesgo de sufrir superposiciones.44____ Programaci6n shell en Unix/Linux sh, ksh, bash Las figuras 9 y 10 presentan el mecanismo interno ascciado al comando siguiente: § find / -name passwd 1> resu 2> resu Primera etapa (ver Figura 9) Tratamiento de la redireccién 1> resu: El shell abre el archivo resu (el archivo se crea con un tamario igual a 0) y lo asocia al descriptor 1 (1, 2, 3, 4, 5). Cuando un proceso abre un archivo, siempre hay un registro asignado en la tabla cle archivos abiertos del nticleo (2) (ésta recoge todas las aperturas de archivo del sistema en un momento dado). El registro contiene el modo de apertura del archivo (en este caso, escritura), asi como la posicién actual dentro del archivo (en este caso, la escritura en el descriptor 1 empezard en el inicio del archive). La posicién 1 (1) de la tabla de descriptores de archivos del proceso contiene un puntero (p2) hacia el registro de la tabla de archivos abiertos. Tratamiento de la redireccién 2> resu: El shell abre de nuevo el archivo resu en escritura (6, 7, 3, 4, 5) (el fichero es sobreescrito, lo que no presenta un problema puesto que el tamafio era 0) y lo asocia al descriptor 2. Un nuevo registro se crea en la tabla de archivos abiertos (p3) (7). Las operaciones de escritura posteriores en el descriptor 2 se harén a partir del inicio del archivo. jObservacion En elcaso de 2>> resu, el archivo se abrié en modo adicién: posicionamiento i final de! archivo (por lo tanto en el byte 0). Las escrituras posteriores en el descriptor 2 garantizan la escritura al final de! archivo. Esta solucion puede producir un resultado aceptable en algunos casos, pero en elresto sigue sien- db incorecta (2 posiciones diferentes). rights reserved (© Editions ENFaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.47 Mecanismos esenciales del shell Capitulo 2 23 elope: ejecucién de find ESPACIO DEL NUCLEO modo: ra PS, do: lect 6 [pe pe modo: escritura offset: of 10 (7) Shell hijo Tabla de archivos abiertos (todos los procesos) ‘archive especial Adev/pts/i 5. [nada dal archivo >| Hev/ots/1 — Pé, 20 bytes de resultados(4) Pp[ inode del archivo resu o 20 Table de los inodos ee bytes de errores(8) errorerrot eautadore| a 10 20 archivo resu Bloques de datos Figura 10: Gestién del posicionamiento en las redirecciones - Segunda etapaaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.75.3 Mecanismos esenciales del shell Capitulo 2 Algunos apuntes sintacticos — En la primera sintaxis, la etiqueta debe estar obligatoriamente pegada al margen izquierdo. — En la segunda sintaxis, el hecho de colocar un cardcter - delante de la etique- ta permite al usuario poner la (iltima etiqueta después de una o varias tabu- laciones. — Las etiquetas tienen que estar seguidas inmediatamente de un salto de linea. Cierre de un descriptor Descriptor) sintaxis Efecto cerrado 0 comando <&- |La entrada estandar del comando se cierra, con lo que no se podré usar para recibir mas datos. 1 lcomando >&- La salida estandar del comando se cierra, icon lo que no se podré usar. Ningin men- saje se podrd mostrar por pantalla. 2 lcomando 2>&- jLa salida de error estandar del comando se cierra, con lo que no se podré usar. Ningdn mensaje de error se podré mostrar por pan- talla. Tubetias de comunicacién Una tuberia (pipe en inglés) permite la comunicacién entre dos procesos. La tuberfa se representa con una barra vertical (pulsar [Alt Gr] 1 en un teclado QWERTY) situada entre dos comandos Unix. El resultado del comando de la izquierda va a parar a la tuberia, mientras que el comando de la derecha leerd Jos datos que hay en ella para tratarlos. Las figuras 12 y 13 representan el mecanismo intemo asociado a la tuberfa de comunicacién. 51aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.55 Mecanismos esenciales del shell Capitulo 2 Segunda manera El comando no recibe ningtin nombre de archivo como argumento. En este caso, el comande tratard los datos que le lleguen por su entrada estandar. Elemplo El comando we cuenta el nimero de lineas que llegan por su entrada esténdar y muestra el resultado por su salida esténdar: $ we -1 entrada de datos por el teclado (Entrada esténdar) entrada de datos por el teclado (Entrada estandar) entrada de datos por el teclado (Entrada estandar) “a (Entrada estandar) 3 (Entrada esténdar) $ Por lo tanto es posible colocar este comando detras de una tuberia: $ who | we -1 4 $ 4Cémo saber si un comando lee su entrada estandar? Accontinuacién se muestran dos métodos que permiten saber si un comando Jee su entrada estandar: ~ La informaci6n estd en el manual del comando. Ejempio A continuacién se detalla una parte del manual del comando we. Se constata que elargumento [ file ... ] es opcional, lo que es una pri- mera sefial. $ man we SYNOPSIS we [-c | -m | -c) [ -lw] [ file...)aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.59 Mecanismos esenciales del shell Capitulo 2 bin:x:1:1:bin: /bin: /sbin/nologin jaemon: /sbin: /sbin/nologin 4:adm: /var/adm: /sbin/nologin Ma&s-~ (438) 8.3 Complementos 8.3.1 Encadenar tuberias Se pueden encadenar mtiltiples tuberfas en una linea de comandos. Ejemplo Mostrar el ntimero de conexiones del usuario cristina: l $ who | grep cristina | we -1 3 8.3.2 Duplicar las salidas Elcomando tee permite visualizar un resultado por pantalla y guardarlo ala vez en un archivo. Ejemplos El comando tee muestra por su salida estGndar las lineas extraidas de la tuberia y las escribe en el archivo listaarch. Si listaarch ya existe, se sobreescribe: $ 1s | tee listaarch Desktop Desktop FIC archivo $aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.Mecanismos esenciales del shell Capitulo 2 23 etapa: Ejecucién del comando date ksh PID=205 Q 1 q forkcteme (5) v date Tabla de PID=206 archivos abiertos d (nucleo) i kee offset (6) mt? @) > 63 archivo resultado (4) Figura 15: Primer ejemplo de agrupacién con parémesis - Segunda etapaaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.67 Mecanismos esenciales de! shell Capitulo 2 Las figuras 19, 20, 21 y 22 representan el mecanismo interno asociado a las Haves. EL shell de trabajo guarda una copia de sus asociaciones descriptor- archivo actuales (1), trata el mismo la redireccién solicitada (2), se duplica para la ejecucién del comando externo date (5) y después, cuando éste tiltimo ha terminado (7), se duplica de nuevo para ejecutar 1a (8). Cuando los comandos han terminado, el shell de primer nivel retoma el control (10) y restaura su entorno descriptor-archivo (11). {date ; Is; } > resultado 12 etapa: Guardar copie del descriptor 1 1 | ——+ /dev/pts/1 La asociacién descriptor 1 - “/dev/pts/1" se quarda (1) Figura 19: Primer ejemplo de agrupacién con laves - Primera etapaaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.Capitulo 3 Configuracién del entorno de trabajo 1. Variables de entorno lL Los temas abordados en este capitulo permitirén al usuario configurar su entorno de trabajo teniendo en cuenta el shell utilizado. Se definen una serie de variables en el entorno del shell. Estas continen la informacién necesaria para el funcionamiento del intérprete y/o de los comandos ejecutados por éste. Listado de variables El comando set devuelve la lista de las variables definidas en el shell actual. $ set HOME=/home/cristina LOGNAME=cristina PATH=/usr/bin:/bin PS1='$ ' PS2='> * TERM=vt100 73aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.81 Configuracién del entorno de trabajo. Capitulo 3 JObservocién Las secuencias de escape deben ir siempre entre comillas (simples o dobles). Elemplo Prompt de bash as Modificar el prompt de tal manera que aparezca el nombre de la maquina sequido del directorio actual: $ PS1='\he@\ws * /home/cristina rumbae-$ 1s -1 diwxr-xr-x 2 cristina cristina 4096 dic 1:16:22 C drwxr-xe-x 2 cristina cristina 4096 oct 23 2001 Desktop rumba@~$ cd ¢ rumba@~/C$ cd /tmp Eumbae/tmp$ JObservecién El caracter ~ representa en bash y en ksh el directorio de inicio del usuario. 1.4.5 PS2 Esta variable contiene la cadena de caracteres que representan el prompt secundario. Este aparece cuando los elementos de la sintaxis shell estan incompletos. Primer ejemplo Mientras que el shell no encuentre la comilia de clerre, espera la continua- cién del comando: $ echo ‘Impresién del carécter * > yo > tengo que > cerrar la comilla' (Final del comando) Impresién del carécter * (Resultado de 1a ejecucién)aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.90____Programacién shell en Unix/Linux sh, ksh, bash $ ls -1 resu SE Endre: 1 cristina cristina 8 ene 31 17:04 resu $ cat resu Hola 8 El archivo resu se sobreescribira: § echo Adiés > resu $ cat resu Adios 8 Activacion de |a opcidn noclobber: 1 & set -o noclobber imposible sobreescribir resu: $ echo Gracias noclobber > resu ksh: resu: file already exists § cat resu Adiés $ Para forzar la sobreescritura, hay que usar la redireccién >| $ echo Gracias noclobber >| resu $ cat resu Gracias noclobber $ La opcién noclobber est desactivada por defecto. 2.3.3 emacs y vi Estas opciones permiten configurar la llamada a comandos (ver Histérico de comandos en este capitulo) ~ En ksh, estas dos opciones estan desactivadas por defecto. — En bash, la opcién emace esté activada por defecto. © Editions ENI- All rights reserved2.3.4 3.1 a Configuraci6n del entorno de trabajo. Capitulo 3 xtrace. Esta opci6n se usa en programacién shell para debuguear los scripts (ver capi- tulo Las bases de la programacién shell - Correccién de un script). Esta opcién. esta desactivada por defecto. Los alias ksh [bash El shell ofrece un comando interno alias que permite crear atajos a coman- dos. Un cierto numero de alias existen por defecto. Definir un alias Ejemplo Creacién de tres alias: 1, ¢, y rmque seran respectivamente los equivalentes Gls -l,clearyrm - $ alias ls'ls -1' $2 total 30 lcristina curso 11428 Ene 28 06:19 out 1 cristina curso 22 Ene 31 17:08 out2 lcristina curso 18 Nov 15 20:08 primero lcristina curso 51 Ene 28 06:22 resu cstclear! xms'rm -i! $ xm out rm: remove out (y/n)? n92-___ Programacién shell en Unix/Linux sh, ksh, bash 3.2 Visualizar Ia lista de alias 3.2.1 Visualizar todos los alias $ alias autoload='typeset -fu! c=clear functions='typeset -f£' history='fc ~1!' integer='typeset -i' je'ls -1' local=typeset ‘fc -e -' tem -1' re x 3.2.2 Visualizar un alias en particular § alias 1 le'ls -1! $s 3.3 Eliminar un alias § unalias 1 a ksh: 1: not found $ 4. Histérico de comandos ksh bash. El shell almacena los comandos ejecutados en un archivo de texto localizado en el directorio de inicio del usuario. El nombre de este archivo difiere en funcién del shell utilizado. © Editions ENI - All ights reserved93 Configuracién del entormo de trabajo. Capitulo 3 Shell Archivo histérico ksh -sh_history bash “bash_history Para recuperar los comandos almacenados en este archivo, shell oftece dos opciones: emacs y vi. Estas dos opciones son mituamente excluyentes: la activaci6n de una desac- tiva la otra. En ksh, ambas estan desactivadas por defecto. En bash, la opcion emacs esté activada por defecto. Configuracién por defecto en ksh: $ Bet -0 Current option settings emacs off vi off Configuracién por defecto en bash: $ Bet -o Current option settings emacs on vi oft s94___ Programacién shell en Unix/Linux sh, ksh, bash 4.1 Configurar la recuperacién de comandos en ksh 4.1.1 Opeién vi EI shell ofrece el uso de comandos idénticos a los que tiene el editor vi para recuperar y, eventualmente, modificar los comandos almacenados en el archivo ~/.sh_history. Para ello es necesario activar la opci6n: $ set -o vi MObservacion i cardcter ~ representa en bash y en ksh e! directorio inicial del usuario, A partir de este momento, hay que imaginarse que se est4 dentro del editor vi. Ciertas acciones se ejecutan en modo comando, otras en modo insercién. La tabla siguiente agrupa los comandos principales que permiten gestionar el histdrico. Acciones en modo inser Esta es modo por defecto, El modo inserci6n permite introducir o modificar un comando Acci6n Comando Introducir un cardcter Caracter deseado [Ejecutar el comando Intro Pasar a modo comando ESC Quitar el significado especial del cardcter siguiente Av Quitar el significado especial de los caracteres "kill" (~u) y \ erase’ (“ho ~2) (© Exitions EN! - All rgnts reservedaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.100____Programaci6n shell en Unix/Linux sh, ksh, bash 4.3.1 Completar en bash Elemplo A continuacién se muestra la lista de los archivos del directorio actual: gis f1 fic2.txt fic3.txt fic.txt prog.c Tecleando la primera letra de un nombre de archivo seguida del caracter de tabulacién (), el bash completa automaticamente la entrada por el nombre del archivo del directorio actual que comience porla letra "p", con la condicién de que el directorio no contenga mas de uno, que es el caso que nos ocupa: [sls p@ Completado de bash: $ 1s prog.c Cuando hay miitioles posibilidades, el shell no completa: 1 $ ls fic Bash no hace nada: § 1s fic Si el usuario apreta dos veces al tabulador, el shell muestra las distintas Posibilidades: $ le HePD fic2.txt fic3.txt fic.txt El usuario completa el nombre del archivo con un conjunto de caracteres discriminantes, seguidos de una tabulacién: [$ ls £102 Completado de bash: $ ls fie2.txt Cuando un archivo completado es un directorio, el shell afiade una final de la cadena: $ touch repi/fl.c rep1/£2.¢ $ mkdir repi $ ca re Completado de bash: $ cd repi/ (© Eomons ENI- All rats reserved43.2 101 Configuracién del entorno de trabajo Capitulo 3 Lo que permite, si es necesario, encadenar otra peticién de completado: § 1s repl/£ Sls rr? Completado de bash: § 1s rep1/ fl.c f2.¢ Completar en ksh Modo vi Los ejemplos siguientes muestran las teclas que permiten gestionar el comple- tado de los nombres de archivo cuando un usuario trabaja con ksh configurado en modo vi (set -o vi). Ejlemplo La lista de los archivos del directorio actual es la siguiente: $ ls f1 fic2.txt fic3.txt fic.txt prog.c Tecleando la primera letra de un nombre de archivo seguido de (Escape) \. elksh completa automaticamente la entrada por elnombre del archivo del directorio actual que comienza por la letra "p", con la condicién de que el directorio no contenga mas de uno, que es el caso que nos ocupa: I $ 1s p[Escape]\ Completado de ksh: $ ls prog.c Cuando hay multiples posibilidades, apretar (Escape)= permite listar las distintas posibllidades: $ 1s £[Escape]= Lista las distintas posibilidades a) f1 2) £ie2.txt 3) £ic3.txt 4) fic.txt Modo emacs Los ejemplos siguientes muestran las teclas que permiten gestionar el comple- tado de los nombres de archivo cuando un usuario trabajacon ksh configurado en modo emacs (set -o emacs).102____ Programacién shell en Unix/Linux 43.3 sh, ksh, bash Ejempio La lista de los archives del directorio actual es la siguiente: Sls fl fic2.txt fic3.txt fic.txt prog.c Tecleando |a primera letra de un nombre de archivo seguido de dos pulsa- ciones sobre (Escape), el ksh completa automaticamente Ia entrada por el nombre del archivo del directorio actual que comienza por la letra "p", con la condicién de que el directorio no contenga més de uno, que es el caso que nos ocupa: I & 16 plZecape] [Recape] Completade de ksh: $ le prog.c Cuando hay multiples posibiidades, la tecla (Echap)= permite listar las distintas posibilidades: $ 1s £[Bscape] [Escape] Ninguna reaccién por parte de ksh $ 1s £[Escape]= Lista las distintas posibilidades v £2 2) £ic2.txt 3) fic3.txt 4) fic. txt Tabla resumen bash ksh modo emacs|ksh modo vi) (Completado simple de una eS [Escape] [Escape] |[Escape]\ "palabra" (tabulacién) Mostrar la lista de archivos Oe [Escape] = {Escape]= que empiezan por "palabra" © Eaitions EN - All rights reserved5. Configuracién del entorno de trabajo. Capitulo 3 . Los archivos de entorno Caracteristicas de los archivos de entorno Los archivos de entorno sirven para almacener de manera permanente las definiciones vinculadas a la configuracién del entoro de usuario. Contienen comandos Unix y siempre se interpretan por un shell. Estos son los scripts shell de entorno. Algunos scripts de entorno sdlo se ejecutan por el shell de conexién. Por tanto, es importante saber distinguir un shell de conexin de un shell normal. Shell de conexi6n Entorno de texto En un entorno de texto, el shell de conexién se ejecuta inmediatamente después de la identificacién del usuario por el nombre de login y su contrasefia. Este proceso es el ancestro comin de todos los comandos que se ejecutaran durante la sesi6n. Todo shell ejecutado posteriormente no tendré el estatus de shell de conexién. Entome grafico En un entorno gréfico, el shell de conexi6n se ejecuta entre la pantalla de conexién y la visualizaci6n del escritorio. Por lo tanto éste no es un shell inte- ractivo. El escritorio y toda aplicacion ejecutada posteriormente a partir de los iconos son procesos descendientes del shell de conexion. En la mayorfa de los casos, un terminal abierto desde el entorno grafico no se considera un shell de conexién. Sin embargo, ciertas plataformas permiten ejecutar desde el escritorio o bien un shell de conexién (ej: icono Consola en Solaris), o bien un shell ordinario (
(umask «..) HERENCIA: @y - Variables oxportadas - Pardmetros del sistema (umask ...) HERENCIA: @) - Variables exportadas - Parématros del sistema umask Figura 7: Sesidn utilizando un Bourne Shell 5.3 Sesién utilizando un Korn Shell Las definiciones de variables y pardmetros de usuario deben realizarse en el archivo ~/.profile, las opciones y alias seran almacenados en otro script cuyo nombre se deja a elecci6n del usuario (por convenio ~/.kshre). La figura 8 representa el transcurso de una sesién de trabajo usando Korn Shell. Comportamiento de un Korn Shell de conexién ~ Se ejecuta después de la identificacién (1). — Lee el script de sistema /etc/profile (2), seguidamente el script de usuario ~/.profile si esta presente: el shell de conexion guarda la definicién de las variables (exportadas 0 no) y de los parémetros del sistema. © Editions ENI - All rights reservedConfiguracién del entomo de trabajo Capitulo 3 — Sila variable ENV esta definida (3), ksh considera que su valor representa el nombre de otro script shell que debe leer. En general, se le da a este archivo el nombre .kshre. Este dltimo est4 cocebido para tener las definiciones de las opciones y alias (4). JObservacién La variable ENV no esta definida por detecto. E] ksh muestra seguidamente su prompt (salvo en entorno grafico donde el escritorio se ejecuta rapidamente), Las variables de entorno, parémetros, opciones y alias se aplican a nivel del shell de conexién (5). Comportamiento de un Korn Shell ordinario (no conexién) Un ksh lanzado posteriormente (6): ~ Recibiré autométicamente el valor de los pardmetros de sistema y de las variables exportadas (7). — Sila variable ENV se ha recibido (para ello, es necesario que haya sido expor- tada a nivel del archivo .profile), el ksh leerd el archivo cuyo nombre est4 contenido en ella, en este caso .kshre (8). Ksh muestra seguidamente su prompt. Las variables de entorno exportadas, pardmetros, opciones y alias se aplican a nivel de este nuevo shell (9). JObservecién Un shell ordinario (de no conexidn) ne lee NUNCA el archivo .profile. 109110____Programacié6n shell en Unix/Linux sh, ksh, bash login: passwd: 1 Contenido del archivo a @ profile Jete/orofile ‘profile. — { ENV=HOME/ kshre export ENV @) Contenido del archivo ENV est definida kshre Lectura del archivo .kshro set -o emacs) (4) lias _aese alias B=AN alias —c 45) El ksh de conexién tiene integrados: =1a definicion de las variables no exportadas =a definicién de las variables exportadas (como ENV) = el nuevo valor de los parémetros de sistema (umask = la definicién de las opciones y de los alias (como ta configuracidn dei histérico de comandos) | (6) 1 HA HEREDADO: (7) + Variables exportadas (coro ENY) - Pardmetres del sisterna (umask ...) (8) Corteniée del archivo ENV ests dofinida: Lectura del archiva kshre « ESTE KSH Ha HEREDADO: La definicign de las variables exportedes (como ENV) + El nusve valor de los parsmetros del sistema (umask...) ESTE FSH HA INTEGRADO: = La definicén de las apoones y de los al (come la configuracién del histérica de comandos) Figura 8: Sesion utilizando un Korn Shell © Editions ENI - All rights reseedConfiguracién del entorno de trabajo. Capitulo 3 5.4 Sesi6n utilizando un Bourne Again Shell Las definiciones de variables y de pardmetros de usuario tienen que realizarse en el archivo ~/.bash_profile, las opciones y los alias estardn en otro script que el usuario Hamaré ~/.bashre. — El bash de conexion lee autométicamente el archivo .bash_profile, pero no el archivo .bashre. — Un bash ordinario (no de conexién) e interactivo lee automdticamente el archivo ~/.bashre. ~ Un bash ordinario y no interactivo (bash que va a ejecutar un script shell) lee el archivo cuyo nombre se cita en la variable BASH_ENV (que tiene que estar definida en el archivo .bash_profile). Esto permite inicializar las variables de entorno tnicamente para el contexto de ejecucién del script shell. Este caso no se tendré en cuenta en el ejemplo siguiente. La figura 9 representa la manera que el entorno tiene que configurarse para que las variables, parametros, opciones y alias se tengan en cuenta en todos los bash interactivos. Comportamiento del Bash de conexién — Se ejecuta justo después de la fase de identificacién (1). ~ Lee el script de sistema /etc/profile, seguidamente abre el script de usuario ~/.bash_profile si existe (2) - Elcomando . ~/,bashre (3) se ha afiadido para solicitar al bash de conexién Ja lectura del archivo -bashre a fin de integrar la definicién de los alias y de las opciones. ~ Una vez el archivo .bashre ha sido lefdo, el bash de conexién lee la conti- nuaci6n del archivo .bash_profile (4). El bash muestra seguidamente su prompt. Las variables de entorno, pardme- tros, opciones y alias han sido actualizados a nivel del bash de conexién (5). inh112___Programaci6n shell en Unix/Linux sh, ksh, bash Comportamiento de un Bash interactivo ordinari Un bash ejecutado posteriormente recibira autométicamente el valor de los pardmetros del sistema y de las variables exportadas (6) y leerd automética- mente el archivo ~/.bashre si este existe (7). El bash muestra seguidamente su prompt. Las variables de entomo, pardmetros, opciones y alias han sido actualizados a nivel de este nuevo shell (6, 8). fogin: pactuds tw Contenido dsl archivo Contenido del archive @) Jeicdoroie >/hash.profie > (8) El bash de conexién ha integrado: : las variatles ro exportedas : rémetroz del sistema (umask...) + la definicion de las opciones y los alias \ . Jarables exportadas arametos celsizere (umask ..) ro) Lecura del archivo beshre (ales eo naclobh @ Este shell ha integrade: “La defnicén de las opciones yde los ales Figura 9: Sesién utilizando un bash © Editions EN) ~All rights reservedaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.119 Las bases de la programacisén shell Capitulo 4 Definicién de la variable var: $ varedefinida $ echo §{var:?"variable no definida"} definida $ 2. Sustituci6n de comandos Los caracteres de sustitucién permiten reemplazar un comando por el resulta- do de su ejecucién, Este mecanismo se utiliza para insertar en la linea de comandos Unix el resultado de otro comando. Sintaxis con las comillas invertidas (acento abierlo) comando argumentol “comando” ... argumenton Sintoxis equivalente ksh bash. comando argumentol $(comando) ... argumenton Ejemplos iCémo provocor la ejecucién de los comandos uname -n y logname? $ echo Ud. est& conectado actualmente a la méquina uname -n y ud. es logname Ud. esta conectado actualmente a la m4quina uname -n y ud. es logname $ Hay que poner los comandos entre los caracteres de sustitucién: $ echo Ud. est conectado actualmente a la m&quina “uname -n° y ud. es “lognam Ud. esta conectado actualmente a la maquina rumba y ud. es cristina $ $ echo Ud. est& conectado actualmente a la maquina $(uname -n) y ud. es $(logname)aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.Las bases de la programacién shell Capitulo 4 123 3.3 Las comillas dobles a Las comillas dobles eliminan el significado de todos los caracteres especiales del shell excepto $, °* y $0), \y a sf mismas. Ejemplo Los caracteres >, |, y 'se protegen con el uso de comillas dobles. Los $, $O. y \ conservan su papel. La pentltina comilla doble se protege con la contrabarra: $ echo "> y | se protegen, $HOME se substituye, ¢(logname) se ejecuta, 1a contrabarra protege al carécter siguiente, lo que permite mostrar una \".* > y | se protegen, /home/cristina se substituye, cristina se ejecuta, la contrabarra protege el carécter siguiente, lo que permite mostrar una ". $ BObservaci En la prdctica, es frecuente poner los argumentas del comando eche entre comillas dobles, Recapitulacién Esta tabla agrupa los caracteres especiales del shell vistos anteriormente: Caracteres Significado espacio - tabulacién - salto de linea |Separadores de palabras ena linea de |comandos & Segundo plano [<<< >>> Tuberia y redirecciones Oy |Agrupacién de comandos i Separador de comandos124 Programacién shell en Unix/Linux sh, ksh, bash Caracteres Significado *? 1120 +0 *0 £0 @() |Caracteres de generacién de nombres de archivo syst } Valor de una variable ~~ $0 Sustitucién de comandos | Caracteres de proteccion 5. Interpretacién de una linea de comandos Los caracteres especiales del shell se interpretan en un orden determinado: Ss 2 - : comando | comando ecuencia de interpretacién ; interno | externo 1. Aislamiento de las palabras separadas por los Realizado por el shell cardcteres espacio, tabulacién y salto de linea actual 2. Tratamiento de los caracteres de proteccién ("","", \). 3. Sustitucion de las variables ($) 14. Sustitucién de los comandos (~~ $()) 15. Sustitucién de los caracteres de generacién de nombres de archivo (*, 2, [] etc.) 6. Tratamiento de las tuberias y redirecciones shell shell hijo 7. Ejecucién del comando jactual © Editions ENT - All nights reserved125 Las bases de la programacién shell Capitulo 4 Ejemplo echo !*! y SHOME y * y. S(ouname) > resu v caracteres de proteccién v echo * y SHOME y * y S(1ogname) > resu v variables v echo * y /home/cristina y # y S(logname) > resu * sustitueién de comandos v echo * y /home/cristina y * y cristina > resu v carecteres de generacién de nombres de archivo echo * y /home/cristina y £142 £3 y cristins > resu v redirecciones y tuberiss v asociacién salida esténdar - archivo resu echo y /home/cristina y £1 £2 £9 y cristina v ejecucién del comande echo v echo recibe 9 argunentos: * y /home/cristina y f1 12 £3 y cristina126 Programacié6n shell en Unix/Linux sh, ksh, bash 6. Escritura y ejecucién de un script en shell 6.1 Definicion Un script en shell es un archivo de texto que contiene los comandos Unix intemos o externos asi como palabras clave del shell. No hay ningiin convenio establecido para el nombre de scripts de shell. El nombre de un archivo script de shell puede tener extensidn, pero no es obliga- torio. Sin embargo, generalmente se usa la extension *.sh" (incluso sil script no se interpreta con el ejecutable llamado "sh Ejemplo Acontinuacién se muestra el script primero.sh: $ nl primero.sh 1 pwd 2 cd /tmp 3 pwd 41s s Ejecucién del script: $ ksh primero.sh /home/cristina /emp £1 £2 £3 $ Los comandos se ejecutan secuencialmente. 6.2 Ejecucién de un script por un sheil hijo En la mayoria de los casos, los scripts tienen que ejecutarse a través de un shell hijo como intermediario. Esto tiene como ventaja la no modificacién del en- torno del shell actual. Para ejecutar un script en shell, existen tres métodos que producen un resultado equivalente. © Editions ENI- All rights resened127 Las bases de la programacién shell Capitulo 4 Primer método $ ksh primero.sh Este ha sido el método usado anteriormente. Se invoca al comando keh pidiéndole la interpretacién del script primero.sh. En este caso, el permiso de lectura sobre el archivo primero.sh es suficiente: $ 1s -1 primero.sh crw-r--r-- 1 cristina curso 19 nov 15 19:16 primero.sh Segundo método $ keh < primero.sh El ksh es un programa que lee su entrada est4ndar, por tanto es posible conec- tarle el archivo primero.sh. En este caso, el permiso de lectura sigue siendo suficiente para su correcta ejecucién. Esta sintaxis es poco utilizada. Tercer método $ chmod urx primero.sh $ 1s -1 primero.sh crwxr--r-- 1 cristina curso 19 nov 15 19:16 primero. sh $ primero.sh Este método es el mds usado. En este caso, el script se considera un comando y, por consiguiente, como todo comando externo, es necesario poseer los per- misos de ejecucién sobre el archivo. Por defecto, el script se interpretard por un shell hijo idéntico al shell actual (si el script se ejecuta desde un Korn shell, se interpretaré por un Korn shell, si se ejecuta desde un Bourne shell, se interpretaré por un Bourne shell). Eleccién del intérprete En le primera linea del archivo, la directiva #! permite imponer el intérprete del script. La ruta de éste tendr4 que expresarse como ruta absoluta.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.130____Programacién shell en Unix/Linux sh, ksh, bash $ pwd /home/cristina Cuando la ejecuci6n del script ha terminado, el valor del directorio actual no ha cambiado. En efecto, un script en shell al ser un comando externa, se eje- cuta a través de un shell hijo. Las figuras 1, 2 y 3 representan el detalle de la ejecucién del script primero.sh. Directorio actual Zhome/eristina Directorio actual /home/cristina $pwd (1) /home/cristina $primerosh (2). ———» | Ks" PI 15 #1 /bin/ksh Irome/srsting tod ing <— ome/ersting oud pwd \s Figura 4: Mecanismo interno aplicado al ejecutar un script en shell - Primera parte (A) Antes de ejecutar el script, el usuario provoca la impresién por pan- talla del directorio actual. El comando pwd al ser un comando interno, se ejecuta por el shell actual (PID=201). Por tanto el resultado del comando es /home/cristina. (2) jecucién del script primero.sh. Un script en shell al ser un comando externo, provoca la duplicacién del shell actual. Por tanto, el script se interpretard por el shell hijo (PID=205). EI shell hijo hereda el directo- rio actual de su padre. © Editions EN - All rights reserved131 Las bases de la programacién shell Capitulo 4 (3) El shell hijo (PID=205) ejecuta el comando interno pwd. Por tanto el resultado del comando es /home/cristina. Directorio actual Amp @) ksh Shell hijo PID=205 #1 Aoin/ksh Directors actual T pwd ne = [idan pad ——> /tmp (5) © Beil ey = (an Latee Fin del ; seript duplcasin | pr00207 (8) @ Figura 2: Mecanismo interno aplicado al efecutar un script en shell - Segunda parte (4) El shell hijo (PID=205) ejecuta el comando interno ed. Por lo tanto, es él mismo el que realiza el cambio de directorio. El directorio actual del hijo ahora es /tmp. (5) _Impresién por pantalla del directorio actual: /mp (6) _Ejecucién del comando externo 1s. El shell hijo se duplica a su vez. Por tanto se produce la creacién de un nuevo ksh (PID=207) que hereda el directorio actual /tmp. El nuevo ksh se reemplaza por el eje- cutable 1s, El proceso 1s hereda el PID 207 y el directorio actual /tmp. 1s muestra por pantalla la lista de archivos del directorio /tmp. (7) Cuando el proceso 207 finaliza, se devuelve el control al ksh de PID 205, que prosigue con la ejecucién del script. No hay mas comandos a ejecutar, por lo tanto este ksh finaliza a su vez (8) y el shell de PID = 201 retoma el control.132____Programacién shell en Unix/Linux sh. ksh, bash Directorio actual fhome/cristina $ pwd Jhome/eristina $ primerash fhome/cristina “mp F112 £3 $ pwd (9) /home/cristina Figura 3: Mecanismo interno aplicado al ejecutar un script en shell - Tercera pane (9) Elentorno del shell 201 no ha sido modificado, el resultado del comando pwd es por consiguiente /home/cristina. 6.3 Ejecucién de un script por el shell actual Este método se usa esencialmente en el caso de los scripts de entorno (.profile, kshrc), y de forma més genérica cuando se desea modificar el entorno del shell actual. Para ejecutar un script con el shell actual, hay que usar el comando interno ".". No hace falta activar el permiso de ejecucién en el script pasado como argumento. Ejemplo Mostrar el valor actual de la variable ExINTT: $ env | grep EXINIT EXINIT='set number showmode’ bservacion La variable EXINIT se usa por vi y contiene la lista de las opciones a activar desactivar. Esta variable tiene que exportarse obligatoriamente. (© Eottions EN - ait rgnts reserved133 Las bases de la programacién shell Capitulo 4 E| usuarlo modifica EXINIT en su archivo .profile: $ vi .profile EXINIT='set number showmode autoindent showmatch' export EXINIT 2a Mientras que el shell actual no haya releido el archivo .profile, 1a mocifica- clon no se tendré en cuenta: $ echo $EXINIT set number shownode Provocar la relectura (ejecutar) del archivo .profile en el shell actual: 1S. -profile La modificacién ahora ya es considerada por el shell actual: $ env | grep EXINIT EXINIT='set number showmode autoindent showmatch' |Odservacién Fl argumento del comando . solamente puede ser un script en shell. Mensaje clasico de error: $. .profile ksh: .: .profile: not found $ acho SPATE fast /bin:/bin El ksh no encuentra el archivo .profile ; sin embargo, est4 en su sitio y su nombre es el correto. El problema yace en el hecho que el argumento del comando . (en este caso el archivo .profile) se busca en los directorios citados en la variable PATH. El directorio de inicio del usuario (lugar donde se encuentra el archivo .profile) tiene que estar referenciado para poder usar esta sintaxis. Sin modificar la variable PATH, es posible provocar la relectura del archivo profile expresando su ubicaci6n de forma explicita (mediante la ruta absoluta ola ruta relativa).134____Programacién shell en Unix/Linux sh, ksh, bash Ejemplo $ pwd /none/cristina $ Ruta absoluta al script: I$ . SHOME/.profile Ruta relativa al script: IS. -/-profile WObservacién iNo confundir los .1EI primer . representa el comando interno del shell y ob gatoriamente tiene que tener un espacio a continuacion. ./.profile repre- senta un nombre de archivo expresado con ruta relativa ; el primer. significa directorio actual, el segundo forma parte del nombre del archivo. 6.4 Comentarios Un comentario comienza por el cardcter # y finaliza al final de la linea. Una excepci6n a esta norma: si la primera linea del archivo empieza por #1, el shell espera encontrarse el nombre del intérprete del script justo detrds. Las lineas en blanco asf como las sangrias (espacios, tabulaciones) se ignoran. Ejemplo $ nl primero.sh 1 #! /bin/ksh 2 # Mi primer script 3 # con comentarios 4 pwd # Mostrar el directorio actual 5 cd /tmp # Cambio de directorio 6 pwd 718 # Listado de los archivos del directorio actual $ © Editions ENT - All rights reservedaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.Las bases de la programacién shell Capitulo 4 $ miscriptsh 120 + 24 $0 $1 $20 $3 Lo] * $# vale 3 Figure 5: Pasar tres argumentos por linea de comandos JObservacién Los argumentos de la linea de comandes tienen que separarse los unos de los otros con (ai menos) un espacio o una tabulacién. 7.2 El comando shift El comando shift permite decalar la lista de argumentos una o varias posi- ciones hacia la izquierda. 7.2.1 Sintaxis shift [n] donde n representa el valor del decalado (n vale 1 por defecto). 7.2.2 Principio La figura 6 representa el valor de los parametros posicionales del shell antes (1) y después (3) dela ejecucién del comando shift (2). Los valores resultantes se pierden ; por lo tanto tendrén que ser guardados antes de que se produzca la operacién de decalado si fuera necesario. La ejecucién del comando shift actualiza las variables $1, $2 .. $9, ${10} ..., $#, $* y$@. 137aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.139 Las bases de Ia programacién shell Capitulo 4 7 echo "4" argumento \$4: $4" @ echo "Todos los argumentos \$*: $#" 9 echo -e "Nimero de argumentos \s#: $#n" 10 # Guardar el primer argumento en la variable dir 21 direst 12 # Decalado de 1 posicién a la izquierda 13 shift 14 # Mostrar las variables después del decalado 15 echo -e "Después de shift\n" 16 echo "1* argumento \$1: $2" 17 echo "2° argumento \$2: $2" 18 echo "3* argumento \$3: $3" 19 echo "4* argumento \$4: $4" 20 echo “Todos los argumentos \$*: $*" 21 echo "Nimero de argumentos \$#: $#" 22 # Cambio de directorio 23 ed $dir 24 # Tratamiento de cada archivo contenido en $* 25 for arch in $* 26 do 27 echo "Guardando $arch ..." 29 done Asignacién del permiso de ejecucion: BS chmod u+x decal.sh Ejecuci6n del script: $ decal.sh /tmp £1 £2 £3 £4 £5 £6 Antes de shift 1° argumento $1: /tmp 2° argumento $2: £1 3° argumento §3: £2 4° argumento $4: £3 Todos lcs argumentos ¢*: /tmp £1 £2 £3 £4 £5 £6 NGmero de argumentos §#: 7 Después de shift 1° argumento $1: £1 2° argumento $2: £2140____ Programacién shell en Unix/Linux sh. ksh, bash 3° argumento $3: £3 4° argumento $4: £4 Todos los argumentos $*: £1 £2 £3 £4 £5 £6 Namero de argumentos $4: 6 Guardando £1 Guardando £2 Guardando £3 Guardando f4 Guardando £5 ... Guardando f6 ... s 7.3 Cédigo de retorno de un comando 7.3.1 La variable $7 Todos los comandos Unix retornan un codigo de error. Este es un entero com- prendido entre 0 y 255. Para el shell, 0 representa el valor verdadero (comando ejecutado con éxito), todo valor mayor de 0 representa el valor falso (érror en Ja ejecucién del comando). El eédigo de error del tltimo comando ejecutado se encuentra en la variable especial $? Ejemplo El comando grep retorna verdadero cuando la cadena buscada es encontrada, falso en caso contrario: $ grep cristina /etc/passwd eristina:x:500:500:cristina Lago:/home/cristina: /bin/bash $ echo $7 o $ grep marcos /etc/passwd $ echo $? 1 En el interior de un script en shell, la verificacion del codigo de retorno de un comando permite orientar el flujo de ejecucion. Multiples ejemplos se presen- tarén en este libro. nights reservea7.3.2 141 Las bases de la programacién shell Capitulo 4 El comando exit Un script en shell es un comando, por lo tanto también deberé retornar un cédigo. El comando exit permite terminar un script retornando un cédigo de error. Ejemplo A continuacién se muestra, en forma de pseudo-cédigo, un script que devuelve 0 6 1 en funcién del nimero de argumentos recibidos: Si $# es diferente de 2 entonces Mostrar " Nimero de argumentos incorrecto * exit 1 # Finalizacién del script con devolucién de cédigo 1 (error) finsi # El script ha recibido 2 argumentos, puede efectuar el eratamiento Tratamiento de los argumentos exit 0 # Finalizacién del script con devolucién de cédigo 0 (éxito) JObservacion EI cédlgo de retomo de un script que no llama explicitamente a exit tiene Por valor el cddigo del ultimo comando ejecutado en el interior del script. 7.4 Otras variables especiales 7.4.1 PID del shell intérprete. $$ representa el PID del shell que interpreta el script (ver Figura 7). Esta va- riable guarda un valor constante durante toda la duracién de la ejecucién del script.142____Programacién shell en Unix/Linux sh, ksh, bash $ miscriptsh #1 /bin/ksh echo $$ =————» 205 Figura 7: La variable $$ Ejemplo El script encuentra.sh crea un archivo resultado que tiene un nombre dife- rente cada vez que se ejecuta: § nl encuentra.sh 1 archresu=/tmp/haencontrado. $$ 2 find "$1" -name "$2" 2> /dev/null 1> $archresu echo "Contenido del archivo $archresu: " 4 more $archresu $ Este script recibe dos argumentos: un nombre de directorio y un nombre de archivo. ~ Linea 1: la variable archresu se inicializa con un nombre de archivo conte- niendo el PID del shell intérprete. - Linea 2: el comando find busca los archivos con nombre $2 a partir del directorio $1 y almacena los resultados en el archivo $archresu. ~ Linea 3: se muestra un mensaje por pantalla. ~ Linea 4: el contenido del archivo $archresu se muestra por pantalla. (© Editions ENI - All rights reservedaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.144____Programacién shell en Unix/Linux sh, ksh, bash Ejomplo. Ejecucién de un comando en segundo plano a partir de un script en shell: nl segundoplanc. sh #1 /usr/bin/ksh find / -name $1 1> /tmp/res 2> /dev/null & date echo “##aseeeuneaeeurunesessennenven echo "Resultado del comando ps: " ps EChO UAHAHRRA REE A SEAR RR ASAHI RHE echo "PID de find: $1" exit 0 DNOBIRALLNHED segundoplano.sh passwd dom nov 17 11:18:56 CET 2002 Resultado del comando ps: PID TTY TIME CMD 1299 pts/o 0. 0 bash 21344 pts/0 00:00:00 ksh 2240 pts/0 00:00:00 segundoplano. sh 2241 pts/0 find 2243 pts/0 Ps PID de find: 2241 $ - Linea 2: el comando £ind se ejecuta en segundo plano. EI shell no espera a que termine, pasa al comando siguiente. 1a variable $1 se inicializa con el PID del proceso find (en este caso 2241) ~ Lineas 3 a 5: jecucién de los comandos date y eche en primer plano. ~ Linea 6: ejecucién del comando ps en primer plano, El proceso find, que todavia no ha finalizado, se identifica por el PID 2241. — Linea 8: Se muestra la variable $1. Contiene efectivamente el valor 2241. Un ejemplo de explotacién de esta variable se vera posteriormente (ver capi- tulo Aspectos avanzados de ia programacién shell - Gestién de un proceso en segundo plano). (© Eaitions ENT ~All rights reservedaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.146____ Programacié6n shell en Unix/Linux sh, ksh, bash La primera palabar se almacena en vari, la segunda en var2: S$ read vari var2 Hasta luego $ echo $vari Hasta $ echo $var2 luego La primera palabra se almacend en vari y el resto de la linea en var2: 9 read varl var2 Hasta luego a todo el mundo § echo $varl Hasta § echo $var2 luego a todo el mundo La palabra se almacena en vari y var2 se queda vacia: $ read varl var2 Gracias $ echo $vari Gracias $ echo $var2 $ Esta version de read permite especificar un mensaje de peticién (en ksh solamente): § read vari?gntre un valor: “ Entre un valor: Hola $ echo $varl Hola s bservacion El comando read lee siempre una linea completa (excluyendo él salio de linea). © Editions ENI - All rghtsresewed147 Las bases de la programacién shell Capitulo 4 8.3 Cédigo de retorno El comando read devuelve un c6digo verdadero si no recibe la informacion fin de archivo (materializada por ~d en el teclado). Ejemplos Un valor se ha introducido, read devuelve verdadero; $ read var Aqui mi entrada de datos $ echo $? ° $ echo $var Aqui mi entrada de datos Si el usuario presiona inmediatamente ia tecla (Enter), introduce la cadena vacia. La variable queda vacia pero el cédigo es verdadero. $ echo $var $ Si el usuario pulsa las teclas “d, envia la informacién de Fin de archivo al comando. La variable queda vacia y el cdédigo es falso. § read var a $ echo $7 1 $ echo Svar $ bservacién La variable no contendra nunca 4d. Solamente la verificacién del cédigo puede decir si el usuario introdujo (Enter) o *d.148____ Programacién shell en Unix/Linux sh, ksh, bash bservacion La introducci6n de *d tiene que realizarse al principio de ia linea. 8.4 La variable IFS Esta variable contiene por defecto los caracteres siguientes: espacio, tabula- cidn (\t) y salto de linea (\n). Ejempio El comando ed permite ver el valor de cada byte alojado en rFs (el carae- ter \e permite no recuperar en la tuberia ef salto de linea del comando echo): $ echo "$IFS\c" | od -c 0000000 \c \n 0000003 $ El contenido de la variable IFS puede modificarse, Ejemplo Copia del valor actual de IFS para su restauracién posterior: I § owwrrs-"siFs" Modificacién de IFS: BS resets" El caracter "espacio" se vuelve un cardcter normal, mientras que el cardc- ter." se convierte en el separador de palabras: is reserved $ read varl var2 var3 palabral:palabra2 palabra3:palabra4 $ echo $varl palabral $ echo $var2 palabra? palabra3 $ echo $var3 = § 89 149 Las bases de la programacién shell Capitulo 4 If palabras Restauraci6n de! valor inicial de IFS: 19 1rs="sororFs" HObservacién Las expresiones $IFS y $OLDIFS deben ir obligatoriamente entre comillas dobles para que los caracteres internos no sean interpretados por el shell. . Ejecucién de verificaciones El comando test Este comando permite hacer verificaciones de archivos, de cadenas de carac- teres y de néimeros. Devuelve el cddigo 0 6 1 (verdadero o falso) que el usuario puede consultar mostrando el valor de $?. El comando test ofrece dos sintaxis equivalentes. Sintaxis Primera sintaxis test expresién gunda sintaxis: comando test [ expresién J E] par de corchetes representa el comando test. Los corchetes de apertura y clausura son respectivamente seguidos y precedidos por un espacio. Esta sintaxis es mucho ms agradable de usar.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.151 Las bases de la programacién shell Capitulo 4 ZOpeién Expresién _ | implementada en Cédigo de retorno Bourne shell? =x nombrearch sf Werdadero si el archivo posee el per- miso de ejecucién -u nombrearch. sf |Verdadero si el archivo tiene activo el bit setuid =g nombrearch sf Verdadero si el archivo tiene activo el bit setgid -k nombrearch sf | Verdadero si el archivo tiene activo el sticky bit Varios nombrearch 1 -nt no Verdadero si el archivo nombrearch2 nombrearchi es mas nuevo que el archivo nombrearch2 inombrearch 1 -ot no Verdadero si el archivo nombrearch2 nombrearchi es més viejo que el archivo nombrearch2 nombrearch] -ef no 'Verdadero si los archivos nombrearch2 nombrearch1 y nombrearch2 referencian el mismo inodo (enlaces fisicos) -O nombrearch no Verdadero si el usuario es el propie- tario del archivo |-G nombrearch no | Verdadero si el usuario pertenece al grupo propietario del archivo Ht [dese] Pi Veradero si el descriptor (I por defecto) est asociado a un terminalaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.153 Las bases de la programacién shell Capitulo 4 9.1.3 Verificaciones de cadenas de caracteres Una cadena puede estar compuesta de cualquier secuencia de caracteres (in- cluido cifras). Expresi6n Cédigo de retorno -z cad |Verdadero si la cadena es de longitud 0 (-z:cero) -ncad1 Verdadero si la cadena no es de longitud 0 (-n:no cero) cad1 = cad2 |Verdadero si ambas cadenas son iguales cad] != cad2 'Verdadero si ambas cadenas son diferentes cad] Verdadero si la cadena no est vacia bservacién Se recomienda poner e! nombre de las variables entre comillas dobles. En efecto, si una variable est vacia, 1as comilias dobles permiten transtormar la expresién en un cadena de longitud 0 (ver ejemplos siguientes). Si una variable vacia no esta entre comillas dobles. su substitucién no devuelve nada (es como si no hubiera habido un nombre de variable). jEn este caso, el comando test mostrard un error de sintaxis! Ejemplos Inicializaci6n de des cadenas: $ cadi=root $ cad2scristina Las dos cadenas no son iguales: $ [ "$cadl" = "$cad2" ] $ echo $7 1 cad! no esta vacia, la verificacién devuelve por lo tanto verdadero: $ test -n "fcadi" $ echo $? 0 saa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.156 Programacién shell en Unix/Linux sh, ksh, bash Ejemplos El comando test devuelve verdadero si $archive no es un directorio: $ archivos/ete/passwa $ [1 -d $archivo ] $ echo $? 0 $ El comando test devuelve verdadero si $dir es un directorio y si el usuario tiene el permiso de recorrerlo; $ dir=/tmp $ echo $dir /emp S$ { -d $dir -a -x $dir ] $ echo $? ° $ Es posible modificar la prioridad de los operadores usando los paréntesis: 1S [ -w Sarchi -a \( -e $dirl -o -e $dir2 \) ] jObservacion Los paréntesis no tienen que ser interpretados por el shell (agrupamiento de comands), sino por el comando test. Por jo tanto tienen que protegerse. jObserva Tiene que haber un espacio alrededor de los operadores 1, -a y -o. 9.1.6 Ejemplo concreto de uso El comando test se usa con las estructuras de control. La estructura de control if se presenta a continuaci6n con el fin de ilustrar el comando. rights reseveo La estructura de control if if comando1 then comandoz © Eaitions EN157 Las bases de la programacién shell Capitulo 4 comando3 else ‘comando4 fi ° if comandol ; then comando2 comando3 else ‘comando4 fi El principio esl siguiente: el comando situado a la derecha del 4£ (comandol) se ejecuta. Si el cédigo de retorno del comando ($? vale 0) es verdadero, la pri- mera parte del i£ se ejecuta (comando2 y comando3). En caso contrario ($2 es mayor que 0), es la segunda parte la que se ejecuta (comando4). La parte else es opcional. Ejemplo Un script en shell que verifica el numero de argumentos recibidos: $ nl testarg.sh 1 #! /usr/bin/ksh if [ $# -ne 2] then echo "Uso: $0 arg] arg2" exit 1 fi echo "El némero de argumentos es correcto" 8 exit 0 $ testarg.sh archi arch? El niimero de argumentos es correcto $ echo §? # Estado de retorno del script (exit 0) 0 § testarg.eh archi Uso: testarg arg] arg2 saaeen158____Programacié6n shell en Unix/Linux sh, ksh, bash | $ echo $7 # Estado de retorno del script (exit 1) 1 s 9.2 El comando (()) ksh Joash El comando [[ }] es una version enriquecida del comando test. Los opera- dores presentados anteriormente (ver seccién El comando test de este capftu- Jo) son también validos (salvo -a y ~o). bservaci6n Los operadores l6gicos -a y -o han sido reemplazados por && y | |. Funcionalidades suplementarias en referencia al comando test Vetificaciones sobre cadenas Las comillas dobles alrededor de los nombres de variables ya no son obligatorias. Ejemplo Sintaxis correctas para verificar si una cadena esté vacia: § echo $vacia test -2 "$vacia" echo $7 (-2 "Svacia" ] echo $7 Ul -z $vacia 1] echo $7 [f -= "gvacia" 1] © Editions ENI ~All rights reservedLas bases de la programacién shell Capitulo 4 159 $ echo §7 ° $ [f $vacda = "* J] $ echo $7 0 — Nuevos operadores han sido afiadidos. Operadores Cédigo de retorno suplementarios cadena = patron Verdadero si cadena coincide con el patton cadena != patron __| Verdadero si cadena no coincide con el patron cadenal
cadena2 —_‘[Verdadero si cadenal es lexicogrficamente poste- rior a cadena2 Usando las expresiones vistas en el capitulo Mecanismos esenciales del shell - Sustitucién de nombres de archivos, es posible comparar cadenas en relacién aun patrén. La tabla siguiente recuerda los caracteres especiales que se pueden usar en los patrones de cadenas de caracteres. Caracteres especiales para patrones de cadenas de caracteres| Significado Caracteres especiales validos en todos los shells: Oa ncaracteres 7 T cardcter cualquiera [abc] 1 caracter de los citados entre los corchetes {labe] ‘1 caracter que no forme parte de los citados entre los corchetes Caracteres especiales no validos en Bourne Shell (en bash activar la opcion extglob: shopt -s extglob). expression) [La expresiOn aparece 0 6 1 vecesaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.161 Las bases de la programacién shell Capitulo 4 Entre un ndmero: +456 4456 ca un nimoro $ test_num.sh Entre un nGmero: -456 -456 es un nimero $ test_num.sh Entre un nGmero: 78* 78* no es un nGmero $ test_num.sh Entre un nimero: az78 az78 no es un nimero $ Ver icaciones jicas — Los operadores ~a y -o se reemplazan por && y | |. — Los paréntesis no tienen necesidad de estar protegidos. Comando test ([]) Comando [[ ]] Significado () [Agrupacién de expresiones 7 1 Negacion pa RR FY Tégico -o il 0 Tegico Eiemplo Con el comando test: if € -w archi -a \( 2 ¢diri -© © sdir2 \) 1 | then Conelcomando [f 1]: if ([ -w farchi g@ ( -e $dirl || -e sdir2) 11 thenaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.Las bases de la programacién shell Capitulo 4 Operadores Significado |Operadores aritméticos Inum1 + num2 Suma numi -num2 Resta numl \" num2 Multiplicacion num / num2 Division num 1 % num2 IMédulo Operadores de comparacion num1 \> num2 \Verdadero si numl es estrictamente mayor que num2 numi \>= num2 \Verdadero si numd es mayor o igual que num num] \< num2 \Verdadero si num es estrictamente menor que inum2 num] \<= num2 Verdadero si num1 es menor o igual que num2 num1 = num2 \Verdadero si numl es igual a num2 num] != num2 Verdadero si num] es distinto de num2 Operadores Iégicos cadenal \& cadena2 \Verdadero si ambes cadenas son verdaderas (valor distinto de cadena nula y 0) cadena! \| cadena2 \Verdadero si una de las cadenas es verdadera (valor distinto de cadena nula y 0) Operadores varios -num1 (Opuesto de num1 \(expresion \) Agrupacion cadena: expresion_regular (Compara Ia cadena con la expresion regular (se Imostrar4n ejemplos en el capitulo Expresiones regulares). 165166 Programacié6n shell en Unix/Linux sh, ksh, bash Los argumentos del comando expr tienen que estar separados por lo menos de un espacio 0 una tabulacién. Ejempios Suma: $ xel $ expr $x + 2 3 Sintaxis incorrecta: el comando recibe un solo argumento que se interpreta como una cadena de caracteres: 142 | $ expr $x+2 $ El caracter * se interpreta por el shell (reempiazado por Ia lista de archivos del directorio actual) antes de la ejecucién del comando expr: $ expr §x * 2 expr: syntax error El cardcter * tiene que protegerse: S$ expr $x \* 2 2 $ Recuperar el resultado del comando dentro de una variable: $ expr $x - -6 7 § res="expr $x - § echo $res 7 Agrupacidn de expresiones: S$ ys2 $ res="expr Sy \* 3+ 1° # Eguivalente a res="expr \( sy \* 3 \) + 17167 Las bases de la programacién shell Capitulo 4 $ echo ¢res 3 $ res="expr Sy \* \( 3 + 1 \)~ $ echo $res iLos ejemplos presentados a continuacién muestran que no hay que confun- dir la salida del comando con su cdédigo de retorno! EI valor mostrado por una comparacion no representa el volor verdadero de la verificacién: $ x=1 $ expr $x \>= 0 1 # Valor mostrado $ echo $7 0 # Cédigo de retorno En este ejemplo, la impresion por pantalla del comando expr nose explota, por lo tanto la salidia estandar se redirige hacia /dev/null: $ nl mayorque.sh 1 #1 /usr/bin/keh # Verificacién del nimero de argumentos if {[ $# -ne 2 }] ; then echo "Ntmero de argumentos incorrecto" echo "Uso: $0 num1 num2” exit 1 fi # Comparer numl y num2 con expr if expr $1 \> $2. > /dev/null 21 then 12 echo “expr: $1 es mayor que $2" 13 fi Beeraueen 14 # La verificacién también puede realizarse con [[ ]] (e £1) 15 if Ef $1 -gt $211 16 then168___Programacién shell en Unix/Linux sh, ksh, bash 17 echo “[{ 1]: $1 es mayor que $2" 18 fi $ $ mayorque.sh 4 2 expr: 4 es mayor que 2 [fl]: 4 es mayor que 2 s 11.2 El comando (()) ksh |bash 11.2.1 Sintaxis ((expresién_aritmética)} 11.2.2 Uso Este comando presenta mejoras respecto al comando expr: — Tiene multitud de operadores. ~ Los argumentos no tienen que estar separados por espacios. ~ Las variables no requieren estar prefijadas por $. — Los caracteres especiales de shell no tienen que protegerse. ~ Las asignaciones se realizan dentro del comando. ~ Su ejecucién es més répida. El comando recupera una gran parte de los operadores del lenguaje C. Operadores Significado Operadores aritméticos Inumi + num2 Suma Inum1 - num2 Resta Inumi * num2 Muitiplicacion Division Inum1 / num2 I rights reserved (© Editions ENLas bases de la programacién shell Capitulo 4 Operadores Significado Inum1 % num2 Médulo Gperadores a nivel de bit ~numi Complemento a 1 num1 >> num2 [Decalado de num1 con num2 bits hacia la derecha numl << num2 |Decalado de num1 con num2 bits hacia la izquierda num & num2 Y bit a bit num | num? (O bit a bit Inumi ~ num2 ‘O exclusivo bit a bit Operadores de comparaci6n num1 > num2 \Verdadero si num1 es estrictamente mayor que num2 num1 >= num? \Verdadero si numi es mayor o igual que numa num1 < num2 \Verdadero si num1 es estrictamente menor que mum Inuml <= num? )Verdadero si num es menor o igual que num2 num1 == num2 |Verdadero si num1 es igual a num2 num1 != num2 'Verdadero si num1 es distinto de num2 Operadores logicos Thum [inversion del valor logico de num1 ER ry Ul O (Operadores varios -numi (Opuesto de numa num = expresion __ |Asignacion (expresion) Agrupacion um binop= num binop representa un de los operadores siguientes: +, -,*, /,%, >>, <<, &, |, *. Esta escritura es equiva- lente a: num1 = num1 binop num2 169aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.173 Las bases de la programacién shell Capitulo 4 13. Cortreccién de un script El shell propone algunas opciones que permiten corregir scripts de shell. 13.1 Opcién -x La opcién -x permite visualizar los comandos que son ejecutados, es decir, después del tratamiento de los caracteres especiales del shell. Primera sintaxis Activar la opeién: set -x Desactivar la opcién: set +x Segunda sintaxis ksh |bash Activar la opcién: set -o xtrace Desactivar la opcién: set +0 xtrace Tercera sintaxis Invocar el shell intézprete con la opcién -x: $ keh -x scriptaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.176 Programacié6n shell en Unix/Linux sh, ksh, bash 13.2 Otras opciones i Bourne shell, Funci6n ksh, bash ksh, bash Lectura de comandos sin ejecutarlos. set -n set -0 noexec Deteccidn de errores de sintaxis del shell.|set +n set +0 noexec Escritura de los comandos antes dela __|set -v set -o verbose substitucién de caracteres especiales del |set +v set +0 verbose shell. Ejempio Deteccién de un error de sintaxis del sheli en Ia linea 4 (faltan las comillas dobles), sin lanzar la ejecucidn del script: § nl muestra.sh 1 @ynusun #1! /usr/bin/ksh echo “Nombre del archivo que se visualizara: \c" read arch if [{ -f "Sarch 1] ; then cat $arch else echo “Archivo inexistente" fi $ keh -n muestra.sh muestra.sh[9 s syntax error at line 9: °"' unmatched z 5 814 14.1 77 Las bases de la programacién shell Capitulo 4 Las estructuras de control if La estructura de control if permite realizar verificaciones. El comando situado tras la palabra if se ejecuta. En funcién del cddigo devuelto por éste, el shell orienta el flujo de ejecucién en la parte then si el comando ha devuelto ver- dadero ($? vale 0) y en la parte else si el comando ha devuelto falso ($? > 0). Si el comando ha devuelto falso y no tiene parte else, el flujo de ejecucién continua con el primer comando situado bajo £4. Primera sintaxis af comandol then comando2 comando3 else comandos fh Segunda sintaxis La parte else es opcional. if comandot then comando2 comando3 th Tercera sintaxis Es posible usar la palabra clave elif que significa sino si. 4f comandol then comando?178____ Programacié6n shell en Unix/Linux sh. ksh, bash elif comando3 then comando4 elif comandos then comandos else conando? fi BObservacién La palabra clave £1 representa el cierre del if, La palabra clave 3e1i£ no tiene clere. Otras sintaxis La palabra clave then puede colocarse en la primera linea con la condicién de usar un ; para poder separar el comando. if comandol ; then comando2 fi También es posible anidar structures de control. La sintaxis mostrada a continuacién es equivalente a la sintaxis e14£ presentada con anterioridad, if comandol then comando2 else if comando3 then comando4 else if comandos then comandoé © Eaitions EN! - All rights reservedaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.372____Programacién shell en Unix/Linux sh, ksh, bash 5.4 Copia fisica, tranformaciones: dd El comando ad realiza una copia fisica de un flujo de entrada hacia un flujo de salida. Cada byte deseado del flujo de entrada se copia hacia el flujo de salida, independientemente de lo que represente el dato. Sintaxis dd [ if-archivo_de_entrada ] [ of=archivo_de_salida | [ibs-numbytes] (obs=numbytes] [bs-numbytes] [skip=numbloques] [seek=numblogues] (count=numbloques] Principales opciones: ifsarchivo_de_entrada Archivo a tratar. Si no se especifica ninguno, se procesara la entrada estandar. ofsarchivo_de_salida Archivo de salida. Si no se especifica ninguno, sc usaraé la salida estandar. ibs=numbytes Tratar los datos de entrada en bloques de numbytes bytes (por defecto: 512 bytes) . obs=numbytes Escribir los datos de salida en bloques de numbytes bytes (por defecto: 512 bytes). bs=numbytes Tratar los datos de entrada y salida en bloques de numbytes. skip=numbloques Saltar numblogues en la entrada antes de empezar el proceso. seek=numbloques En la salida, escribir desde el bloque numbloques. count=numbloques Escribir unicamente numbloques de entrada hacia la salida. jempios Copia de un disco en otro disco en bloques de 6 kilobytes: I # dd if-/dev/dsk/c0t0d0s2 of=/dev/dsk/cOtid0s2 bs=8k (© Eaitions ENI ~All rights resewedaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.382____Programacién shell en Unix/Linux 7.1 sh, ksh, bash, El usuario cristina de la maquina pluton puede conectarse a la maquina venus con Ia cuenta de olivia, sin tener que introducir una contrasena. cristinagpluton$ ssh -1 olivia venus Last login: Wed Jan 9 22:30:33 2008 from xx.xx.20%x.xx Linux 2.4.34.5. § Un ejemplo de uso no interactivo del comando sftp se muestra en el capitulo Aspectos avanzados de la programacién shell - Script de archivado incremen- tal y transferencia sftp automatica. Otros comandos El comando xargs El comando xargs, colocado detras de una tuberfa recupera las cadenas pasa- das por argumento de la entrada esténdar y ejecuta comando2 pasindole estas cadenas como argumento. Sintaxis comandol | xargs [ opciones ] comando2 Principales opciones: ot Muestra el o los comandos realmente ejecutados (registro de la ejecucién). -n nunarg comando2 s6lo recibiré numarg argunentos y se ejecutara tantas veces como sea necesario. En los siguientes ejemplos, el comando time se usa para medir el tiempo de ejecucién de un comando. El resultado se interpreta de la siguiente manera: ~ user : tiempo de ejecucién de cédigo de usuario. = sys : tiempo de ejecucién del cédigo del nucleo. ~ real ;duraci6n total de la ejecucién (user + sys + inactividad). (© Eaitons EN - Al nents reservedaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.398____ Programacié6n shell en Unix/Linux | sh, ksh, bash \f, 25 \h, 80 en sed, 294 &-, 234 kK comando (()), 169 comando [[ J], 161 operador de shell, 162 &1,48 &2, 48 #, 134 en awk, 307 #1, 22 #7, 252 ¥ expresién regular, 277 +(expresién) comando {[ J], 160 con case, 182 nombres de archivo, 31 redireccién awk, 312 =,74 % > : redireccién awk, 312 g >> 3 redirecci6n awk, 312 : [51 a é 5 :aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.——————————————————————————————————————————————————— 402____ Programacién shell en Unix/Linux sh, ksh, bash Caracteres especiales del shell, 123 expresiones regulares, 273 Caracteres especiales de shell recordatorio, 389 case, 181 cat, 340 cat -v, 98 ed, 21,27 chmod, 127 close, 330 emp, 384 Cédigo de retorno de un script en shell, 141 Comando externo, 19 filtro, 339 interno, 21 orden de interpretacién, 393 red, 374 Comando interno recordatorio, 390 Comentario, 134 Comilla doble, 123 invertida, 119 comm, 385 Completar de bash, 99 en ksh, 101 continue, 199 Contrabarra, 122 Correcci6n, 173 cos, 325 Criterios de seleccién en awk, 304 sh, 16, 17 © Editions ENI ~All rights reservedaa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book.406____Programacién shell en Unix/Linux sh, ksh, bash iconv, 374 if, 2Z en awk, 316 uso con test, 156 IFS, 145, 148, 242 ignoreeof, 89 Impresi6n por pantalla, 23 index, 324 INT, 247 int, 325 KILL, 248 Korn Shell, 16 de conexién, 108 ordinario, 109 sesidn utilizando un, 108 ksh, 16, 17 ksh 88, 16, 17 ksh 93, 16 Lectura del teclado, 145 length, 324 let, 171 Linea de comandos orden de interpretacién, 124 Linux, 16 Llaves, 66 log, 325 © Editions ENI ~All rights reservedRecursos Informaticos Redes, sistemas, programacion, SGBDR, tecnologias Internet o intranet, informatica industrial... Los Ambitos que abarca la informatica técnica siguen la evoluci6n de las tecnologias, siendo cada dia més variados y complejos. Esta evolucion amplia los campos de aprendizaje de los nuevos expertos € impone a los profesionales una continua adaptacién de sus conocimientos. ia N Redactados por formadores profesionales y consultores, los libros de la coleccién Recursos t informaticos le aportan una ayuda eficaz para descubrir y aplicar diferentes técnicas. La presentacion de los conceptos bésicos, de numerosos ejemplos y los consejos de expertos garantizan la calidad y riqueza de cada uno de estos libros. Programacién shell en Unix/Linux - sh, ksh, bash Este libro de programacién shell va dirigido a usuarios y administradores Christine DEFFAIX REMY de sisternas Unix/Linux que desean aprender a programar scripts shell. _Ingeniera informatica en,la empresa Se detallan las funélefalidades de tres shells, usados habltualmenie yc< Ociensa Technologies) especialista sus diferencias. Los conceptos se presentan de manera proaresiva y & [a administracién y Galt petiagégica, convirtfendo este libro en un soporte ideal destinado tanto & Unix y Linux, Christine Deffalx 2 la formacién profesional como ala autoformacién: Bi ee lene on teas ee Los primeros capitulos tratan sobre el funcionamiento del shel: ejecu- _T2l'0y formacién en grandes ven Gin de un comand, caraceres especiales cel sll sadeshabiualmente— US use experiencia ut (redirecciones, woer{as,...), configuracién del entorno de trabajo del tionan’ una obra realmente. eficar usuario (variables y archivos.de entorno,...). Los mecanismos internds'S@ cara el aprendigaje en la creacién explican detalladamente y se ilustran con maittiples esquemas. de scripts shell A continuacién, el libro se centra en la programacién propiamente dicha Se presentan e ilustran las bases de la programacién (variables, estructu ras de control, comandos de verificacién y cAlculo,...) mediante una gran cantidad de ejemplos y, més adelante, se detallan los aspectos avanzados de la programacicn shell (gestién de archivos, funciones,...) La Gitima parte trata sobre las utilidades anexas indispensables para el tra- tamiento de cadenas de caracteres y de archivos de texto: las expresiones regulares basicas y extendidas, el editor no interactivo sed, una visién exten- dida del lenquaje awk y los principales comandos filtro de los sistemas unix En www.ediciones-eni.com: * Flemplos de scripts shell 0 awk. ISSN 1629-7458 ISBN: 978-2-7460-7623-5 ESE, Los ejemplos de scripts shells 0 awk usados en produccién incluidos rel —— SY libro se pueden descargar en www.diciones-eni.com = S Renn ——. Prélogo = Introducci6n + Mecanismos esenciales del shell + Configuracén del —_———< entorno de trabajo + Las bases dela pragramacién shell + Aspectos avanzada de —=<— la programacién shell « Expresiones regulares « I comando sed + Elenquaje eo ——h pprogramacion awk + Los comandes fluo + Anexos eni vw.ediciones-eni.com Lediciones
También podría gustarte
Arden, Paul - Usted Puede Ser Lo Bueno Que Quiera Ser (2005) PDF
PDF
97% (64)
Arden, Paul - Usted Puede Ser Lo Bueno Que Quiera Ser (2005) PDF
67 páginas
Alemany Carlos - 14 Aprendizajes Vitales
PDF
80% (5)
Alemany Carlos - 14 Aprendizajes Vitales
314 páginas
Miguel Serrano - La Resurreccion Del Heroe
PDF
100% (2)
Miguel Serrano - La Resurreccion Del Heroe
58 páginas
Waldo Emerson Ralph - Confianza en Uno Mismo
PDF
Aún no hay calificaciones
Waldo Emerson Ralph - Confianza en Uno Mismo
40 páginas
Conocimiento Prohíbido (Traducción de Adela Kaufmann)
PDF
100% (3)
Conocimiento Prohíbido (Traducción de Adela Kaufmann)
16 páginas