Beruflich Dokumente
Kultur Dokumente
Objetivos:
- Entender el uso de scripts in sistemas Linux.
- Aprender comandos y sintax de Bash shell
- Formar programas con lenguaje de programacin de Bash
#!/bin/bash
# cleanup, version 2
# Ejecutar como root
LOG_DIR=/var/log
ROOT_UID=0
#
LINES=50
#
E_XCD=66
#
E_NOTROOT=67
#
# or
if [ "$PWD" != "$LOG_DIR" ]
# Not in /var/log?
then
echo "Can't change to $LOG_DIR."
exit $E_XCD
fi # Doublecheck if in right directory, before messing with log file.
tail -$lines messages > mesg.temp # Saves last section of message log file.
mv mesg.temp messages
# Becomes new log directory.
cat /dev/null > wtmp #
echo "Logs cleaned up."
exit 0
Un valor cero desde el script cuando exit indica exito. el simbolo #! en primer linea indica que
el fichero es listo para un conjunto de comandos. En realidad es un nmero magico de dos
bytes que indica el tipo de fichero.
#!/bin/sh
#!/bin/bash
#!/usr/bin/perl
#!/usr/bin/tcl
#!/bin/sed -f
#!/usr/awk -f
Llamando el script
sh < scriptname >
chmod 555 scriptname (gives everyone read/execute permission)
chmod +rx scriptname (gives everyone read/execute permission)
chmod u+rx scriptname (gives only the script owner read/execute
permission)
Caracteres Especiales
\# Comentarios
; Separador de Comandos. Permite dos o ms comandos, echo hola; echo buenos
;; Terminador de sentencia case [Double semicolon]
Considera la siguiente ejemplo:
case "$variable" in
abc) echo "$variable = abc" ;;
xyz) echo "$variable = xyz" ;;
esac
En esta ejemplo, utilizamos full quoting. Si tenemos 'STRING' preserva todos los caracteres
especiales dentro de STRING. El operador coma: El operador coma enlace operaciones
aritmeticas; para que todos estan evaluadas, pero solo se devuelve el ltimo
Tiene la misma efecto que cat /dev/null >data.xxx Pero no va a fork un procesos nuevo,
debido que ":" es una funcin builtin. La caractera ":" tambien sirve como separador de campo
en /etc/passwd, y en la definicin del variable de entorno $PATH.
var1=5
var2=23skidoo
echo $var1
echo $var2
# 5
# 23skidoo
${parametro} Es lo mismo que $parametro, eg. , el valor del parametro de variable. Se puede
utilizarlo para concatenar variables con cadenas. En bash las cadenas y expresiones
numericos se trata en una manera similar.
your_id=${USER}-on-${HOSTNAME}
echo "$your_id"
#
echo "Old \$PATH = $PATH"
PATH=${PATH}:/opt/bin #Add /opt/bin to $PATH for duration of script.
echo "New \$PATH = $PATH"
Ejecutar COMMANDS para cada miembro en WORDS, con NAME enlazada al miembro actual
for i in vacas cabritos cerdos pollos
do
echo ``$i es un animal de granja''
done
echo -e pero \n GNUs no son ''
Sentencias Condicional: if
if TEST-COMMANDS; then
CONSEQUENT-COMMANDS;
[elif MORE-TEST-COMMANDS; then
MORE-CONSEQUENTS;]
[else ALTERNATE-CONSEQUENTS;]
fi
Ejecutar selectivamente los COMMANDS basada sobre WORD que match PATTERN.
La barra $|$ esta utilizado para separar patrones multiples.
Funciones de Shell
[`function'] NAME () { COMMAND-LIST; }
#!/bin/bash
function quit {
exit
}
function hola {
echo Hola!
}
hola
quit
echo foo
#!/bin/sh
if test ``$1'' = ``'' ; then
echo ``Usage: backup-lots.sh <filename>''
exit
fi
for i in 0 1 2 3 4 5 6 7 8 9 ; do
NEW_FILE=$1.BAK-$i
if test -e $NEW_FILE ; then
echo ``backup-lots.sh : warning $NEW_FILE''
echo ``
already exists''
else
cp $1 $NEW_FILE
fi
done
Ejecutar selectivamente los COMMANDS basada sobre WORD que match PATTERN.
La barra $|$ esta utilizado para separar patrones multiples.
Variables
IFS
PATH
HOME
CDPATH
MAILPATH
PS1
PS2
OPTIND
OPTARG
Ejemplos
# cleanup: Un script para limpiar los ficheros log en /var/log
# Ejecutar como root
cd /var/log
cat /dev/null > messages
cat /dev/null > wtmp
echo "Los logs esta limpia."
script.
if [ -n $1 ]
# Test if command line argument present.
then
lines=$1
else
lines=50
# default, if not specified on command line.
Fi
cd /var/log
tail -$lines messages > mesg.temp
# Saves last section of message log file.
mv mesg.temp messages
# cat /dev/null > messages
# No longer needed, as the above method is safer.
cat /dev/null > wtmp
echo "Logs cleaned up."
exit 0
# A zero return value from the script upon exit
# indicates success to the shell.
Endless loop:
while :
do
operation-1
operation-2
...
operation-n
done
if condition
then :
# Do nothing and branch ahead
else
take-some-action
fi
${parameter-default}
${parameter=default}
${parameter+otherwise}
${parameter?err_msg}
#!/bin/bash
: ${HOSTNAME?} {USER?} {MAIL?}
echo $HOSTNAME
echo $USER
echo $MAIL
echo Critical env. variables set.
exit 0
Sustitucin y expansin
Ejemplo
#!/bin/bash
var1=abcd-1234-defg
echo "var1 = $var1"
t=${var1#*-*}
echo "var1 (with everything, up to and including first - stripped out) = $t"
t=${var1%*-*}
echo "var1 (with everything from the last - on stripped out) = $t"
path_name=/home/bozo/ideas/thoughts.for.today
echo "path_name = $path_name"
t=${path_name##/*/}
# Same effect as
t=`basename $path_name`
echo "path_name, stripped of prefixes = $t"
t=${path_name%/*.*}
# Same effect as
t=`dirname $path_name`
echo "path_name, stripped of suffixes = $t"
t=${path_name:11}
echo "$path_name, with first 11 chars stripped off = $t"
t=${path_name:11:5}
echo "$path_name, with first 11 chars stripped off, length 5 = $t"
t=${path_name/bozo/clown}
echo "$path_name with bozo replaced = $t"
t=${path_name//o/O}
echo "$path_name with all o's capitalized = $t"
exit 0
Grupo de Comandos
(.)
Grupo de comandos. \texttt{(a=hello; echo \$a)}
{ .} Bloque de cdigo. Crea un funci\'on anonimo. Bloque de codigo puede tener E/S
rediricionado desde y hacia el.
#!/bin/bash
# Bloques de cdigo y E/S redireccin
{
read fstab
} < /etc/fstab
echo "Primer linea de /etc/fstab es:"
echo "$fstab"
exit 0
Redireccin
The concept of a standard input and a standard output is one of the most useful features of
UNIX-like operating systems. The idea is that every program, no matter how diverse, should be
reading input and generating output in a uniform, clearly understood way. Once you have that, it
makes it much easier for programs to talk to one another directly. It is also possible to write generic
programs that bridge the input and output of any two programs, which is an amazingly handy ability
to have.
Send standard output to a file.
>
<
2>
>>
|
tee
script Save the activity on your screen in a file.
xargs Read multiple arguments from standard input and use them as arguments to
some specified command.
scriptname >filename
command >&2
scriptname >>filename
<<
|
>|
-
redireccionar stdin
Tuberia. Salida de un comando a otro o shell
forzar redirecci\'on. Sobre-escribir un fichero existente.
redirecci\'on desde/hacia stdin or stdout.
Ejemplos:
echo ls -l | sh
Redireccin y ficheros
Hay tres descriptores de ficheros: stdin, stdout y stderr
1 representa stdout
2 representa stderr
grep da * 2> grep-errors.txt
grep da * 1>&2
Tuberias
ls -l | sed -e "s/[aeio]/u/g"
ls -l | grep "\.txt$"
Acceder Parametros
$0, $1,etc. parametros positional (desde linea de comandos o desde funcin, o
un variable)
$#
numero de argumentos o parametros posicional en linea de comandos
$$
id de proceso de script, utilizado a menudo en scripts para construir nombre de
ficheros temporal
$?
estatus de salida (exit) de funcin o de script
$*
todo los parametros positionales
$@
lo mismo de $*, pero para cada parametro es un string en comillas
$flags passed to script
$!
PID de ltima job ejecutando en fondo
=
asignacin de variables (no espacio antes y despues de &)
Obtener valor de return de un programa
Valor de salida return value de una programa esta guardad en un variable especial, denomida
$?.
Ejemplo de como capturar valor de salida:
#!/bin/bash
cd /dada &> /dev/null
echo rv: $?
cd $(pwd) &> /dev/null
echo rv: $?
Comparicin de Cadenas
s1 = s2 s1 igual a s2
s1 != s2 s1 no es igual a s2
s1 < s2
s1 > s2
-n s1 s1 no es null
z s1 s1 es null
#!/bin/bash
S1='string'
S2='String'
if [ $S1=$S2 ];
then
echo "S1('$S1') no es igula a S2('$S2')"
fi
if [ $S1=$S1 ];
then
echo "S1('$S1') es igual a S1('$S1')"
fi
Sentencia de if/then
#!/bin/bash
if [ condition-true ]
then
command 1
command 2
...
else
# Opcional para anadir mas chequeos
command 3
command 4
...
fi
if [ -x filename ]; then
elif
if [ 0 ]
then
echo "0 es verdad."
else
echo "0 es falso."
fi
if [ ]
#NULL (empty condition)
then
echo "NULL es verdad."
else
echo "NULL es falso."
fi
if [ xyz ]
#string
then
echo "string aleatorio es verdad."
else
echo "string aleatorio es falso."
fi
#!/bin/bash
a=4
b=5
Logical Operators
#!/bin/bash
echo Logical Operators
a=3
echo a = $a
b=`expr $a \> 10`
echo 'b=`expr $a \> 10`, therefore...'
echo "If a > 10, b = 0 (false)"
echo b = $b
b=`expr $a \< 10`
echo "If a < 10, b = 1 (true)"
echo b = $b
-ne (!=)
Comparison Operators
#!/bin/bash
echo Comparison Operators
echo
a=zipper
echo a is $a
if [ `expr $a = snap` ]
# Force re-evaluation of variable 'a'
then
echo "a is not zipper"
fi
String Operators
#!/bin/bash
echo String Operators
echo
a=1234zipper43231
echo The string being operated upon is $a.
# index: position of substring
b=`expr index $a 23`
echo Numerical position of first 23 in $a is $b.
# substr: print substring, starting position & length specified
b=`expr substr $a 2 6`
echo Substring of $a, starting at position 2 and 6 chars long is $b.
# length: length of string
b=`expr length $a`
echo Length of $a is $b.
# 'match' operations similarly to 'grep'
b=`expr match $a [0-9]*`
echo Number of digits at the beginning of $a is $b.
b=`expr match $a '\([0-9]*\)'`
echo The digits at the beginning of $a are $b.
exit 0
#!/bin/bash
let a=11
# Same as 'a=11'
let a=a+5
# Equivalent to let "a
# (double quotes makes
echo "a = $a"
let "a <<= 3"
# Equivalent of let "a
echo "a left-shifted 3
= a + 5"
it more readable)
= a << 3"
places = $a"
xargs
[-0prtx] [-e[eof-str]] [-i[replace-str]] [-l[maxlines]] [-n max-args] [-s max-chars][-P max-procs] [-null] [--eof[=eof-str]] [--replace[=replace-str]] [--max-lines[=max-lines]] [--interactive] [-maxchars=max-chars] [--verbose] [--exit] [--max-procs=maxprocs] [--max-args=max-args] [--norun-if-empty] [-version] [--help] [command [initial-arguments]]
Read arguments from standard input, construct a command line using those arguments and
arguments provided on its own command line, and execute the constructed commands.
Example: Suppose you have some time on your hands and you want to grep through every file in
the /usr/local filesystem for the string "datum". First, generate a list of the files using the find
command; then pipe the results of that find to grep via the xargs command. (If you don't use xargs,
grep will look only at the names of the files for the string "datum", and not look in the files
themselves.) In other words, use
find /usr/local -type f -print | xargs grep "datum"
--null, -0
--eof[=eof-str], -e[eofstr]
--help
--replace[=replace-str], i[replace-str]
--max-lines[=max-lines], l[max-lines]
--max-args=max-args, -n maxargs
--interactive, -p
--no-run-if-empty, -r
--msax-chars=max-chars, -s
max-chars
--verbose, -t
--version
--exit, -x
--max-procs=max-procs, -P
max-procs