Programacion en bash

Programación en Bash

Que es Bash ??
Bourne-Again SHell (otro shell bourne) Haciendo un juego de palabras (born-again significa renacimiento) sobre el Bourne shell (sh), que fue uno de los primeros intérpretes importantes de Unix. Hacia 1978 el shell Bourne era el shell distribuido con el Unix Version 7.

Stephen Bourne, por entonces investigador de los Laboratorios Bell, escribió el shell Bourne original . Brian Fox escribió el shell bash en 1987. En 1990, Chet Ramey se convirtió en su principal desarrollador. BASH es el shell por defecto en la mayoría de sistemas GNU/Linux, además de Mac OS X Tiger, y puede ejecutarse en la mayoría de los sistemas operativos tipo UNIX. También se ha portado a Microsoft Windows por el proyecto Cygwin. Es un Interprete de comandos. no necesita compilar :D

Stephen Bourne, por entonces investigador de los Laboratorios Bell, escribió el shell Bourne original . Brian Fox escribió el shell bash en 1987. En 1990, Chet Ramey se convirtió en su principal desarrollador. BASH es el shell por defecto en la mayoría de sistemas GNU/Linux, además de Mac OS X Tiger, y puede ejecutarse en la mayoría de los sistemas operativos tipo UNIX. También se ha aportado a Microsoft Windows por el proyecto Cygwin.

Como encontrarlo ??

Aplicaciones -> accesorios -> Terminal
Tecleamos:

im@Bucio-Ju4×0r:~$ locate bash

Para ser mas exactos:

im@Bucio-Ju4×0r:~$ which bash
/bin/bash

Que necesito saber antes de crear mi primer script?

  1. Editor de texto, gedit, vim etc..
  2. Comandos Básicos Unix.
  3. Ganas de aprender :D.

Comandos Basicos

* Cambiar el directorio de trabajo (change directory):
$ cd
* Listar el contenido de directorios (list):
$ ls
* Crear un directorio (make directory):
$ mkdir
* Borrar un directorio (remove directory):
$ rmdir
* Copiar un archivo o directorio en el directorio especificado (copy):
$ cp
* Mover un archivo o directorio a un archivo o directorio. Se utiliza también para renombrar; el origen y destino es un archivo (move):
$ mv
* Borrar archivos o directorios (remove):
$ rm <opciones> <archivo>
* Mostrar por pantalla el contenido de los archivos por la salida estándar. Si no se especifica ningún archivo, la orden repite todo lo que se ha escrito por la entrada estándar. Para indicar que se ha acabado de escribir hay que pulsar CTRL+D.
$ cat
* Buscar archivos recorriendo árboles de directorios especificados por las rutas, evaluando de izquierda a derecha las condiciones de búsqueda. Además se pueden especificar acciones sobre los resultados obtenidos:
$ find
* Mostrar el nombre del directorio en el que uno se encuentra situado (print working directory). Se dice que ese directorio es el directorio de trabajo:
$ pwd
* Cambiar los permisos de el archivo.
$chmod <PERMISOS> <ARCHIVO>
*Sacar por la salida standard (la pantalla) lo que se le pasa por parámetro, puede ser texto o una variable
$echo Hola echo hola > hola.txt

Estructura.

#!/bin/bash #! Se conoce con el nombre de Sha Bang.
/bin/bash Lo que vamos a usar ya sea bash o perl (/usr/bin/perl)
#
# Esto es un comentario
#

comando
comando
comando
…..

HOLA MUNDOOO

#!/bin/sh
echo ”Hola Mundo, cruel :’(”

EJECUTANDO EL SCRIPT.

im@Bucio-Ju4×0r:~/Conferencias/Flisol 2008/bash$ chmod -x hola.sh
im@Bucio-Ju4×0r:~/Conferencias/Flisol 2008/bash$ ./hola.sh
Hola Mundo, cruel :'(
im@Bucio-Ju4×0r:~/Conferencias/Flisol 2008/bash$

REDIRECIONES.
Existen 3 descriptores de ficheros:
stdin, stdout y stderr (std=estándar).

En los ejemplos :
El número 1 representa a stdout, y 2 a stderr.

REDIRRECIONES

Esto hará que la salida de un programa se escriba en un fichero.
stdout a un fichero

im@Bucio-Ju4×0r:~/Conferencias/Flisol 2008/bash$ ls -l > ejemplols-l.txt

Esto hará que la salida stderr de un programa se escriba en un fichero.
stderr a un fichero

im@Bucio-Ju4×0r:~/Conferencias/Flisol 2008/bash$ grep da * 2> errores-grep.txt

Esto hará que la salida stdout de un programa se escriba en el mismo descriptor de fichero que stderr.
stdout a un stderr
En este caso, la parte stdout del comando se envía a stderr.

im@Bucio-Ju4×0r:~/Conferencias/Flisol 2008/bash$ grep da * 1>&2

Esto hará que la salida stderr de un programa se escriba en el mismo descriptor de fichero que stdout.
stderr a stdout.
En este caso, la parte stderr del comando se envía a stdout

im@Bucio-Ju4×0r:~/Conferencias/Flisol 2008/bash$grep * 2>&1

TUBERÍAS

Las tuberías le permiten utilizar la salida de un programa como la entrada de otro.

enlista | entuba en sed e imprime en pantalla, todo con solo U =)

im@Bucio-Ju4×0r:~/Conferencias/Flisol 2008$ ls -l | sed -e “s/[aeio]/u/g”
tutul 524
-rwxr-xr-x 1 um bucuu 251 2008-04-26 04:25 ulurmu.sh
drwxr-xr-x 2 um bucuu 4096 2008-04-26 19:45 bush
-rw-r–r– 1 um bucuu 142551 2008-04-26 02:46 Bush.udp
-rw-r–r– 1 um bucuu 0 2008-04-26 12:28 urrurus-grup.txt
-rwxr-xr-x 1 um bucuu 55 2008-04-26 10:44 fururur.sh
drwxr-xr-x 2 um bucuu 4096 2008-04-24 18:16 umg
-rw-r–r– 1 um bucuu 129 2008-04-17 02:37 lul.sh~
-rw-r–r– 1 um bucuu 78 2008-04-13 09:35 numbru.sh~
-rw-r–r– 1 um bucuu 42207 2008-04-13 09:02 Puntulluzu-76.png
-rw-r–r– 1 um bucuu 313771 2008-04-26 02:48 prugrumucuununbush08.pdf
im@Bucio-Ju4×0r:~/Conferencias/Flisol 2008$

En este caso, la salida del programa ls -l se envía al programa grep, que imprimirá las líneas que concuerden con la regex (expresión regular) “\.txt$”

im@Bucio-Ju4×0r:~/Conferencias/Flisol 2008$ ls -l | grep “\.txt$”
-rw-r–r– 1 im bucio 0 2008-04-26 12:28 errores-grep.txt
im@Bucio-Ju4×0r:~/Conferencias/Flisol 2008$

EMPEZANDO CON LOS SCRIPTS.

Después de mostrar los comandos básicos y tuberías empece con la acción :D

VARIABLES

#!/bin/sh
nombrevariable=valor #<– declarando variable normal
nombrevariablecomando=’comando’ #<– declarando variable con valor de comando
echo $nombrevariable #<– mandando a llamar variable

VARIABLES INTRODUCIDAS POR EL TECLADO

Script nombre.sh
#!/bin/sh

echo ”hola como te llamas”
read nombre

Script read.sh
#!/bin/sh

echo ”hola como te llamas”
read nombre
echo ”Hola $nombre”

COMANDO READ
-n num_car : Número máximo de caracteres que puedes introducir por teclado
-p “frase” : Te muestra por pantalla una frase para, saber que debes introducir
-d “delimitador” : Especificas cual va a ser el delimitador, es decir si dices que el delimitador sera “;” pues todo lo que venga antes de un “;” lo cogerá una variable y todo lo que venga después de ese delimitador hasta el próximo “;” lo cogerá otra variable

read [opciones] nombre_variable1 nombre_variable2 nombre_variableN
read -p “Introduce el nombre y los apellidos” nombre apellidos

Condiciones, Operadores….

OPERADORES RELACIONALES ARITMÉTICOS
-lt (<)
-gt (>)
-le (<=)
-ge (>=)
-eq (==)
-ne (!=)

OPERADORES ARITMETICOS
+ (adición)
- (sustracción)
* (producto)
/ (división)
% (módulo)

CONDICIONES, BUCLES, CICLOS..
( If – Then )
( While )
(UNTIL)
( FOR )

IF

if [condición]
then
lista de comandos
else
lista de comandos2
fi

Script ifvariable.sh
#!/bin/bash

echo ‘ Adivina el valor numerico de la variable’
read A
if [ $A = 1 ]
then

echo ‘Acertaste’
exit 0
fi
echo
‘No acertaste’
exit

Script ifelse.sh
#!/bin/bash

echo Cual es tu Edad
read edad
if [ $edad -ge 18 ]; then
echo
eres mayor de edad
else
echo
eres menor de edad
fi

FOR
El bucle for es distinto a los de otros lenguajes de programación. Básicamente, le permite iterar sobre una serie de `palabras’ contenidas dentro de una cadena.

SCRIPT for.sh
#!/bin/bash

for i in $( ls ); do
echo item: $i
done

En la segunda línea declaramos i como la variable que recibirá los diferentes valores contenidos en $( ls ).
‘done’ indica que el código que ha utilizado el valor de $i ha acabado e $i puede tomar el nuevo valor.

WHILE
El bucle while ejecuta un trozo de códico si la expresión de control es verdadera, y sólo se para cuando es falsa (o se encuentra una interrupción explícita dentro del código en ejecución).

while [ condición ]; do

done

Script tabla.sh
#!/bin/bash

echo -n Que tabla de multiplicar desea ver
read numero
contador=1
while [ $contador -le 10 ]; do
let multi=$numero*$contador
echo $numero*$contador = $multi

let contador=$contador+1
done

let lo que hace es evaluar arithmeticamente la expresion que sigue.

UNTIL
El bucle until es casi idéntico al bucle loop, excepto en que el código se ejecuta mientras la expresión de control se evalúe como falsa.

script until.sh
#!/bin/bash

CONTADOR=20
until [ $CONTADOR -lt 10 ]; do
echo CONTADOR $CONTADOR
let CONTADOR-=1
done

FUNCIONES

Como en casi todo lenguaje de programación, puede utilizar funciones para agrupar trozos de código de una manera más lógica, o practicar el divino arte de la recursión.

Declarar una función es sólo cuestión de escribir
function mi_func { mi_código }.

script funcion.sh
1 #!/bin/bash
2 function salir {
3 exit
4 }
5 function hola {
6 echo Hola
7 }
8 hola
9 salir

script funcionvariable.sh
#!/bin/bash
function salir {
exit
}
function e {
echo $1
}
e Hola
e Mundo
salir

SELECT
El sueño de un programador para hacer menús basados en texto.
Muy similar a la construcción ‘for’, sólo que en vez de interar para cada ‘palabra’ en $OPCIONES, se lo pide al usuario.

script menuselect.sh
#!/bin/bash

OPCIONES=”Hola Salir”
select opt in $OPCIONES; do
if [ "$opt" = "Salir" ]; then
echo done
exit
elif [ "$opt" = "Hola" ]; then
echo Hola Mundo
else
clear
echo opción errónea
fi
done

BASH EN OTROS LENGUAJES

PERL
#!/bin/bash
#Llamando a un interprete externo a BASH

echo ‘El siguiente texto será mostrado por el interprete de PERL’
perl -e ‘print “Este texto es mostrado por un script PERL embebido.\n”;’
exit 0

PYTHON
#!/bin/bash
#Llamando al interprete de Python.
echo ‘El siguiente es un script de python:’
echo print “Hola, mundo!” | tee $HOME/.testpythonbash.py
python $HOME/.testpythonbash.py
exit 0

Referencias:

http://martinezcampuzano.blogspot.com/2007/08/programacion-en-bash.html
http://es.wikibooks.org/wiki/El_Manual_de_BASH_Scripting_B%C3%A1sico_para_Principiantes
http://www.guia-ubuntu.org/index.php?title=Terminal
http://buntulug.com.ar/wiki/Tutorial_de_Bash
http://es.tldp.org/COMO-INSFLUG/COMOs/Bash-Prog-Intro-COMO/

Fuente


15 Comentarios a “Programacion en bash”

  1. Bucio dice:
    Mozilla Firefox 2.0.0.16 Ubuntu Linux

    :D ahuevo se ve mergas ;)


    Mozilla Firefox 2.0.0.16 Ubuntu Linux

  2. Websites tagged "descriptores" on Postsaver dice:
    PHP

    [...] – Nueva propuesta de explotación de los descriptores: el “Muro” saved by bdchinta2008-08-15 – Programacion en bash saved by [...]


    PHP

  3. mapacheUY dice:
    Mozilla Firefox 3.0.3 Windows XP

    Vale! Muy bueno el post y el sitio también. Adelante.


    Mozilla Firefox 3.0.3 Windows XP

  4. Hector Enrique Peña dice:
    Mozilla Firefox 3.5.6 Windows XP

    muy Apasionante!!!!!!!!!!!!!


    Mozilla Firefox 3.5.6 Windows XP

  5. jhonnybook dice:
    Internet Explorer 6.0 Windows XP

    Free books on programming
    http://goo.gl/vkOMS

    Technology books here


    Internet Explorer 6.0 Windows XP

  6. bookyjhonny dice:
    Internet Explorer 6.0 Windows XP

    Los libros electrónicos aquí!
    http://goo.gl/hdL2a

    Conseguir libros gratis


    Internet Explorer 6.0 Windows XP

  7. bookyjhonny dice:
    Internet Explorer 6.0 Windows XP

    BookGrill – ebooks gratuitos
    http://goo.gl/Ur8iO

    Libros en formato PDF


    Internet Explorer 6.0 Windows XP

  8. JonNagasawa dice:
    Internet Explorer 6.0 Windows XP

    Przede [url=http://www.pomidory.dobrapozycja.net/82338/Meble-dla-dziecka/art.html]Meble dla dziecka[/url]
    dowolnym umeblowanie dziecinne winnom egzystowac [url=http://www.com.com.czest.pl/28608,art,Meble-dla-dzieci.html]Meble dla dzieci[/url]
    dostrojone az do czasu oraz utarczki temuz przychowek. Wypada obliczac sie sposrod tym, iz razem sposrod tym kiedy przychowek zjawiac sie beda sie raz za razem starsze pojawi sie alisci i przymus kupienia gwoli [url=http://www.zarabiaj.prosta-strona.info/a/Meble-dla-dzieci,85874]Meble dla dzieci[/url]
    nich kolejnych sprzetow. Wybierajac umeblowanie la starszych obecnie przychowek nader [url=http://www.webmail.com.czest.pl/26974,art,Meble-dla-dzieci.html]Meble dla dzieci[/url]
    niekongruentnym impulsem istnieje skonsultowanie sie sposrod nimi w watpliwosciach zakutych przed momentem sposrod akuratnym wyborem sprzetow az do ich grotu. Gdyby lazi o nadzwyczaj tyciutkiego dziatwa owo nie ma ani chybi takiej dyspozycja. W tej okolicy zdecydowac musza idea zlotawa temuz rodziciele. Dokonujac odkupow sprzetow, nawet gwoli [url=http://www.mini.wsinf2007.com/art-23416/Meble_dla_dzieci.html]Meble dla dzieci[/url]
    cienkich przychowek [url=http://www.el-dorado.one.pl/15805/Meble-dla-dzieci/artykul.html]Meble dla dzieci[/url]
    wypada zastanowic sie aktualnie o czasie, w jakim czereda te beda starsze. Nierzetelnym konceptem istnieje skutkiem tego przyrzadzanie nadzwyczajnego polozenia w jakim beda zdolaly egzystowac odpracowywane zajecia, alisci takze zas powinno sie istnieje rozwazyc bez watpienia o adekwatnym polozeniu w jakim dziatwa beda zdolalyby sie wykladac. Obligatoryjnym utylitarnie degeneratem zlokalizowania grotu bedzie rowniez , na jakim nie na odwrot bedzie wolno odpracowywac kurs. Winnismy znajdowac sie odrebne [url=http://com.net.bytom.pl/30343,art,Meble-dla-dziecka.html]Meble dla dziecka[/url]
    punkt, na jakim po prostu mozliwe bedzie ustawienie kompa. Z trudem istnieje w tym momencie przedstawic se izba dziecinny bez takiego aparatu, jaki nie na odwrot zapewnia rozgrywki, alisci podczas gdy w najwyzszym stopniu dopuszcza dodatkowo funkcjonalna lekcje. Decydujac sie na umeblowanie gwoli swoich dziatwa nie wolno jednak w malowartosciowym ciosie nie pamietac o materiach spojonych sposrod bezpieczenstwem [url=http://katalog.forcehost.pl/5465,artykul,Meble-dla-dziecka.html]Meble dla dziecka[/url]
    niepolskich latorosli. Postepowego umeblowanie dziecinnego winnom znajdowac sie w tego typu postepowanie stworzone, tak aby przychowek nie zdolaly zdzialac siebie szkody. Na caloksztalt asocjuje owo usuniecia mocnych granicy, jakie zdolaja sie w trafie sprzetow pojawic, jednak nie jest dozwolone rowniez nie pamietac o zapewnieniu niepozostalych sprzetow, jakiego matki w swoim autorskim klanu. Najogromniejsze zagrozenie w casusu dziatwa oprawi sie sposrod sprzetami kuchennymi, w jakich skladowane sa niepewnego w celu [url=http://xn--wizytwki-z3a.bielawa.pl/a/Meble-dla-dziecka,48910]Meble dla dziecka[/url]
    nieciasnych a [url=http://www.peter.only-4u.info/art/Meble-dla-dzieci,14900]Meble dla dzieci[/url]
    ciekawych [url=http://p19.seebaa.pl/a/Meble-dla-dzieci,19354]Meble dla dzieci[/url]
    dziatwa srebro stolowe. [url=http://kws751.nuntek.az.pl/45290,art,Meble-dla-dziecka.html]Meble dla dziecka[/url]
    niebiezacego rowniez oskarzyciela pomocne sypie sie aplikacja [url=http://www.wpis.com.czest.pl/art-28539/Meble_dla_dzieci.html]Meble dla dzieci[/url]
    ponadprogramowych zapewnien jakiego efektywnie beda zdolalyby powstrzymac wysuniecie takiej skrytki z wykorzystaniem tez milusinski. Powinno sie podobnie dowolnego modelu niepewnego cele, jakimi maluch zdolaloby zeby se sprawic [url=http://dw3.duzo.malopolska.pl/artykul-373/Meble_dla_dziecka.html]Meble dla dziecka[/url]
    szkode chronic w regalach a szafkach az do jakich pociecha nie bedzie po prostu w stanie pochwycic. Nawet posada obeznanej [url=http://przepisnasushi.com/96656/Meble-dla-dzieci/artykul.html]Meble dla dzieci[/url]
    przyzwoitce przypadkiem [url=http://yy41.superwiadomosci.pl/a/Meble-dla-dziecka,121229]Meble dla dziecka[/url]
    gdyz wyrazic sie niesatysfakcjonujace az do zapobiegniecia potencjalny kazusom, jakie w trafu czereda zdolaja sie alisci przytrafic, takie pozycje powinno sie dlatego antycypowac [url=http://dobrykatalog.chilitoy.com/artykul-64929/Meble_dla_dziecka.html]Meble dla dziecka[/url]
    .


    Internet Explorer 6.0 Windows XP

  9. jhonnybook dice:
    Opera 7.54 Windows XP

    Libros en formato PDF , para descargar gratis
    http://goo.gl/IaWvV

    Descargue aquí los libros gratis


    Opera 7.54 Windows XP

  10. booky dice:
    Internet Explorer 6.0 Windows XP

    Descargar libros en formato PDF de forma gratuita
    http://goo.gl/D7GP7

    Conseguir libros gratis


    Internet Explorer 6.0 Windows XP

  11. stoostabs dice:
    Opera 7.11 Windows ME

    qeatcc [url=http://redlandsliving.com/]penny auctions[/url] AtZaXaR
    pclQvu penny auctions lycZehX
    iRolXt [url=http://paulchristenbury.com/]make money online[/url] ttpiqhc
    RQsqaX make money online ttpdtXo


    Opera 7.11 Windows ME

  12. booky dice:
    Internet Explorer 6.0 Windows XP

    Libros en formato PDF , para descargar gratis
    http://goo.gl/bUAXm

    Libros en formato PDF


    Internet Explorer 6.0 Windows XP

  13. abalryleque dice:
    Internet Explorer 6.0 Windows 2000

    This kind of text message will provide you with an sincere Meratol review This assists use up more calories as well On the net, you will find product or service assessments about Meratol UK clientele exclusively CaffeineThe quantity of caffeine within Meratol was designed to aid in increasing ability and also staying power during doing exercises if utilized an hour or so ahead of when doing exercises Regrettably, within their bid to accomplish a thing fairly simple, these people obtain duped through unscrupulous manufacturers and greedy internet marketers to generate a rapidly dollar [url=http://meratol.blinkweb.com/]meratol[/url]

    Meratol features a exclusive 4-tier method that’s not within every other weight loss pill Youngsters more youthful when compared with 16 ought to however first seek advice from any adverse health specialist in advance of making use of it The primary operate involving Meratol is to employ our metabolic process to experience a protected excess weight decline Mostly, persons overeat involving large gram calorie goodies in-between meals that are far more full of fats and carbs By having a organic procedure for fat loss, Meratol works together with the metabolism Shedding pounds as of this tempo is obviously directly on the topic of future routine maintenance How excellent this Meratol functions as a supplement?It is known which Meratol contains the right match this that means it is the most effective diet pill Meratol will be the most recent diet capsule to enter this diet market place and holds by it a few committed promises regarding the method it may well moreover enable you to get rid of large quantities associated with bodyweight [url=http://meratol.blinkweb.com/]meratol reviews[/url] The body could plateau, causing you to be thinking exactly why your entire effort is not paying down Meratol is shown to support increase the charge that you can get rid of fat — Utilizing Meratol can assist you to melt away an additional 12x the amount of energy you’d with a typical evening These types of carbs provides the body your all kinds of sugar we want as well as tries to make all of us feel total

    Selected weight reduction items bring about side effects just like immediate requirement for elimination plus bloatedness Your glycoprotein complex which will come through the darkish seaweed ingredients is successful to cut back your absorption involving carbs approximately 82 % It will be possible to close your current carbo ingestion : Within medical studies of those people who purchased Meratol is actually is proven that around 82% coming from all carbohydrates eaten will never be absorbed by your body This could not have already been a tremendous matter besides normally ladies put on pounds if they’re expecting a baby as well as breastfeeding your baby It’s established that fat loss product won’t deliver any side effects Not the same as great deal of the diet goods we normally learn it really is hard to classify Meratol as one of the diet pills, hunger controller or fat binder Certain weight loss goods present regarding unwanted effects similar to critical require for treatment in addition bloating [url=http://meratol.blinkweb.com/]meratol ingredients[/url] Exactly why? For this performs a number of various actions which in turn focus on the major difficulties of extra body fat within you Thus; if you are looking out to get a actually wonderful fat reduction item next obtain Meratol


    Internet Explorer 6.0 Windows 2000

  14. Zooroliaise dice:
    Internet Explorer 6.0 Windows XP 64 bit

    pharmacy grade vitamins http://sundrugstore.net/products/sinemet.htm eviline pharmacy


    Internet Explorer 6.0 Windows XP 64 bit

  15. borokeoy dice:
    Internet Explorer 5.5 Windows 95

    Android libros:
    http://bookgrill.com/?getes.html
    Libros en formato PDF


    Internet Explorer 5.5 Windows 95

Dejar un comentario

Codigo emoticones:
:alien: :angel: :@ ;) :$ :cheerful: :cool: :cry: :devil: :dizzy: :ermm: :face: :getlost: :biggrin: :happy: :heart: :kissing: :lol: :D :ninja: :pinch: :pouty: :sad: :shocked: :sick: :sideways: :silly: :sleeping: :) :P :unsure: :w00t: :S :whistle: :wink: :wub: