viernes, 27 de abril de 2012

Curso scripting Bash part 1

Bash (Bourne again shell) es un programa informático cuya función consiste en interpretar órdenes. Está basado en la shell de Unix y es compatible con POSIX. Fue escrito para el proyecto GNU y es el intérprete de comandos por defecto en la mayoría de las distribuciones de Linux. Su nombre es un acrónimo de 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 Bourne era el intérprete distribuido con la versión del sistema operativo Unix Versión 7. Stephen Bourne, por entonces investigador de los Laboratorios Bell, escribió la versión original de Bourne. Brian Fox escribió Bash en 1987. En 1990, Chet Ramey se convirtió en su principal desarrollador. Bash es el intérprete predeterminado 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 llevado a Microsoft Windows por el proyecto Cygwin.


Bash no le podría ir mejor a Tiempo de Tux ya que bash es para OS tipo Unix y ese es el nucleo del tema de la pagina

Como esto ya es mas avanzado que otros tutoriales del sitio lo voy a explicar de manera normal y puede notarse un poco dificil

1.Ver donde esta Bash

Para saber donde esta Bash teclearemos lo sigiente en terminal

whereis bash
2.Ver versión de bash


echo $BASH_VERSION


3.Uso de hashbang

El hashbang es la ruta donde se encuentra el interprete de nuestro script

Con el comando pasado whereis bash sabemos donde se encuetra

ejemplo

#!/bin/bash

se le añade #! para indicar la ruta del interprete

Esto va hasta arriba de nuestro script

ejemplo

#!/bin/bash
# Texto que quieras (derechos)
contenido

Otro ejemplo


#!/bin/bash


#===================== Info: ===========================#
# Original script name: Setup 1.0 #
# Build number: 38 #
# Installs/Uninstalls: ScreenCapture 1.0 #
# Author: Cooleech #
# Contact author: cooleech@gmail.com #
# Project's homepage: ??? #
# License: GPLv3 #
#=======================================================#


# Load app variables
SCV="1.0" # ScreenCapture version


# Load language variables
case "$LANG" in
*hr*)
NO_XTERM="Izgleda da nemate instaliran xterm koji je nužan za ispravan rad ove skripte! Molim vas, ručno instalirajte xterm te ponovo pokrenite ovu skriptu!"
UNSUPPORTED_PACK_MAN="Vaš sustav koristi nepodržani paketni upravitelj. Molim ručno provjerite imate li na vašem sustavu instaliran zenity i ffmpeg paket!"
NO_FFMPEG="Na vašem sustavu nedostaje ffmpeg paket.\nŽelite li instalirati ffmpeg sada?"
INSTALL_OK="Instalacija je uspjela!"
INSTALL_FAIL="Instalacija nije uspjela!\nMolim pokušajte instalirati ručno!"
DONT_RUN_AS_ROOT="Ovu skriptu nebi smjeli pokretati kao 'root'!\nPokrenite je kao 'obični' korisnik."
UNINSTALL_WARN="<span font_desc=\"Bold 16\">ScreenCapture $SCV Setup</span>"
UNINSTALL_APP="Želite li odinstalirati ScreenCapture $SCV?"
FFMPEG_INSTALLED_AS_DEP="Tjekom instalacije ScreenCapture skripte, također ste instalirali i ffmpeg paket.\n
Želite li ga sada odinstalirati?"
UNINSTALL_OK="Odinstalirano! ;("
INSTALL_INFO="<span font_desc=\"Bold 16\">ScreenCapture $SCV Setup</span>\n\n
ScreenCapture je malena skripta za hvatanje vaše radne površine u video datoteku.
Skripta ovisi o <b>ffmpeg-u</b>, te ukoliko nije prisutan na sustavu, ponudit će njegovu instalaciju.
Ukoliko automatska instalacija ovisnosti ne prođe u redu, molim vas pokušajte ga ručno instalirati!\n
<b>Instalacijom ove skripte automatski prihvaćate uvjete iz GPLv3 licence!</b>"
INSTALL_APP="Želite li nastaviti sa instalacijom?"
RES_ERROR="Došlo je do greške u detekciji rezolucije!
Rezolucija zahvaćanja je postavljena na 1024x768."
PICK_RES="Odaberite video rezoluciju"
TYPE="Tip"
RES_AND_FPS="Rezolucija i broj sličica"
PART_OF_SCREEN="hvata samo dio ekrana"
CUSTOM_RES="Vlastita"
DETECTED_RES="Detektirana"
W_AND_H="Širina i Visina"
MUST_BE_HxW_MAX="Mora biti ŠxV, te djeljivo sa 2\n(MAKSIMALNO"
CAPTURE_INFO="Snimanje zaustaviti sa <b>q</b> (quit) u terminalu!
Također možete otvoriti terminal i upisati: <b>killall ffmpeg</b>
Video snimka će biti u <b>$HOME</b> mapi!\n
Kliknite na 'U redu' za početak snimanja ili\nzatvorite ovu poruku da odgodite snimanje."
DESKTOP_ICON_COMMENT="Snimite prikaz zaslona u video"
;;
*)
NO_XTERM="Looks like you don't have xterm installed which is neccessary for this script to run properly! Please, install xterm manualy and then run this script once again!"
UNSUPPORTED_PACK_MAN="Your system is using unsupported pack manager. Please check manualy if you have zenity and ffmpeg packets installed on your system!"
NO_FFMPEG="Your system needs ffmpeg package.\nWould you like to install ffmpeg now?"
INSTALL_OK="Installation successful!"
INSTALL_FAIL="Installation unsuccessful!\nPlease try to installing it manualy!"
DONT_RUN_AS_ROOT="Do not run this script as 'root'!\nRun it as 'normal' user."
UNINSTALL_WARN="<span font_desc=\"Bold 16\">ScreenCapture $SCV Setup</span>"
UNINSTALL_APP="Would you like to uninstall ScreenCapture $SCV?"
FFMPEG_INSTALLED_AS_DEP="During ScreenCapture installation you also installed ffmpeg package.\n
Would you like to uninstall it now?"
UNINSTALL_OK="Uninstalled! ;("
INSTALL_INFO="<span font_desc=\"Bold 16\">ScreenCapture $SCV Setup</span>\n\n
ScreenCapture is a small script for captureing your desktop in a video file.
Script depends on <b>ffmpeg</b>, and if it's not available on this system, it's installation will be offered.
If dependencie auto-install fails, please try to install it manualy!\n
<b>Installing this script you automaticaly agree to the terms from GPLv3 license!</b>"
INSTALL_APP="Continue with install?"
RES_ERROR="Error occured during detecting screen resolution!
Capture resolution is now set to 1024x768."
PICK_RES="Pick video resolution"
TYPE="Type"
RES_AND_FPS="Resolution and fps"
PART_OF_SCREEN="captures only part of screen"
CUSTOM_RES="Custom"
DETECTED_RES="Detected"
W_AND_H="Width and Height"
MUST_BE_HxW_MAX="Must be WxH, and dividable by 2\n(MAXIMUM"
CAPTURE_INFO="Stop capture with <b>q</b> (quit) in terminal!
Also you can open terminal and type: <b>killall ffmpeg</b>
Video file will be saved in <b>$HOME</b> folder!\n
Click 'Ok' to start capture or\nclose this window to postpone it."
DESKTOP_ICON_COMMENT="Video capture your screen"
esac


# Check xterm
which xterm
if [ $? != 0 ]; then
echo "ERROR: $NO_XTERM"
zenity --error --text "$NO_XTERM"
exit 1
fi


# Check package manager
which apt-get
if [ $? = 0 ]; then
PACK_MAN_INSTALL="apt-get -y install"
PACK_MAN_UNINSTALL="apt-get remove"
fi
which aptitude
if [ $? = 0 ]; then
PACK_MAN_INSTALL="aptitude -y install"
PACK_MAN_UNINSTALL="aptitude remove"
fi
if [ "$PACK_MAN_INSTALL" = "" ]; then
xterm -e "echo $UNSUPPORTED_PACK_MAN
read -p \"\""
fi


# Check zenity
which zenity
if [ $? != 0 ]; then
xterm -e "sudo $PACK_MAN_INSTALL zenity"
which zenity
if [ $? = 0 ]; then
zenity --info --text "Zenity status:\n\n$INSTALL_OK" --timeout=3
else
xterm -e "echo \"Zenity status: $INSTALL_FAIL\""
exit 1
fi
fi


# Check if root
if [ "$UID" = "0" ]; then
zenity --error --text "$DONT_RUN_AS_ROOT"
exit 1
fi


# Check xdg-user-dirs-update
which xdg-user-dirs-update
if [ $? = 0 ]; then
. ~/.config/user-dirs.dirs # Import variables
fi


# Set desktop icon dir
if [ "$XDG_DESKTOP_DIR" = "" ]; then
if [ -d "$HOME/Desktop" ]; then
XDG_DESKTOP_DIR="$HOME/Desktop"
else
XDG_DESKTOP_DIR="$HOME"
fi
fi


# =================================================================== Start GUI =================================================================== #
if [ -e $HOME/.ScreenCapture/ScreenCapture ]; then
# ================================================ Uninstall ScreenCapture script ================================================= #
zenity --question --width=500 --height=350 --title "ScreenCapture $SCV - Setup" --text "$UNINSTALL_WARN\n\n\n\n\n$UNINSTALL_APP"
if [ $? != 0 ]; then
exit
else
. $HOME/.ScreenCapture/setup.rc
if [ "$FFMPEG_INSTALLED" = "TRUE" ]; then
zenity --question --text "$FFMPEG_INSTALLED_AS_DEP"
if [ $? = 0 ]; then
xterm -e "sudo $PACK_MAN_UNINSTALL ffmpeg"
fi
fi
rm -r $HOME/.ScreenCapture
rm -f "$XDG_DESKTOP_DIR"/ScreenCapture.desktop
zenity --info --text "ScreenCapture $SCV status:\n\n$UNINSTALL_OK"
exit 0
fi
# ================================================================================================================================= #
fi


zenity --question --width=500 --height=350 --title "ScreenCapture $SCV - Setup" --text "$INSTALL_INFO\n\n\n$INSTALL_APP"
if [ $? != 0 ]; then
exit
fi


# Create dir if doesn't exist
if [ ! -d $HOME/.ScreenCapture ]; then
mkdir $HOME/.ScreenCapture
fi


# Check ffmpeg
which ffmpeg
if [ $? != 0 ]; then
zenity --question --text "$NO_FFMPEG"
if [ $? = 0 ]; then
xterm -e "sudo $PACK_MAN_INSTALL ffmpeg"
which ffmpeg
if [ $? = 0 ]; then
zenity --info --text "Ffmpeg status:\n\n$INSTALL_OK" --timeout=3
# Dependencies installed info
echo "FFMPEG_INSTALLED=TRUE" > $HOME/.ScreenCapture/setup.rc
else
zenity --error --text "Ffmpeg status:\n\n$INSTALL_FAIL"
exit 1
fi
else
exit 1
fi
fi






# ========================================================= Install ScreenCapture script ========================================================== #
echo "#!/bin/bash


#################################################
# ScreenCapture v1.0 by Cooleech #
# GPLv3! Use it at your own risk! #
#################################################


# Check ffmpeg
which ffmpeg
if [ \$? != 0 ]; then
zenity --question --text \"$NO_FFMPEG\"
if [ \$? = 0 ]; then
xterm -e \"sudo $PACK_MAN_INSTALL ffmpeg\"
which ffmpeg
if [ \$? = 0 ]; then
zenity --info --text \"Ffmpeg status:\n\n$INSTALL_OK\" --timeout=3
# Dependencies installed info
echo \"FFMPEG_INSTALLED=TRUE\" > $HOME/.ScreenCapture/setup.rc
else
zenity --error --text \"Ffmpeg status:\n\n$INSTALL_FAIL\"
exit 1
fi
else
exit 1
fi
fi


# Check and try to get screen resolution
which xrandr
if [ \$? = 0 ]; then
SCREEN_RES=\`xrandr | grep '*'\`
SCREEN_RES=\"\${SCREEN_RES/    */}\"
SCREEN_RES=\"\${SCREEN_RES// /}\"
else
zenity --warning --text \"$RES_ERROR\"
SCREEN_RES=\"1024x768\"
fi


# Resolution and fps mods
RES=\`zenity --width=450 --height=250 --list --radiolist --title=\"ScreenCapture $SCV\" --text=\"$PICK_RES (<b>MAX: \$SCREEN_RES</b>)\" \\
--column \" ? \" --column \"$TYPE\" --column \"$RES_AND_FPS\" FALSE \"PAL\" \"720x576 @ 25 fps, $PART_OF_SCREEN\" \\
FALSE \"NTSC\" \"720x480 @ 30 fps, $PART_OF_SCREEN\" FALSE \"$CUSTOM_RES\" \"???x??? @ 25 fps\" TRUE \\
\"$DETECTED_RES\" \"\$SCREEN_RES @ 25 fps\"\`


# Load selected params
case \$RES in
PAL*)
RES=\"720x576\"
FPS=\"25\"
;;
NTSC*)
RES=\"720x480\"
FPS=\"30\"
;;
$CUSTOM_RES*)
RES=\`zenity --entry --title=\"$W_AND_H\" --text \"$MUST_BE_HxW_MAX \$SCREEN_RES)\" --entry-text=\"\$SCREEN_RES\"\`
if [ \$? != 0 ]; then
exit 1
fi
FPS=\"25\"
;;
$DETECTED_RES*)
RES=\"\$SCREEN_RES\"
FPS=\"25\"
;;
*)
exit 1
;;
esac


# Self-explainable :)
SCRIPT_PATH_AND_NAME=\"\$HOME/ScreenCapture-\$RES@\${FPS}fps\"


# Make capture script
echo \"#!/bin/bash


ffmpeg -f x11grab -s \$RES -r \$FPS -i :0.0 -sameq \\\$HOME/ScreenCapture.mpg
exit 0\" > \$SCRIPT_PATH_AND_NAME
chmod 777 \$SCRIPT_PATH_AND_NAME # Make it executable


# Show info
zenity --info --title=\"\$RES@\${FPS}fps - ScreenCapture $SCV\" --text \"$CAPTURE_INFO\"
if [ \$? = 0 ]; then
xterm -e \$SCRIPT_PATH_AND_NAME
rm -f \$SCRIPT_PATH_AND_NAME # Comment this if you don't wish to auto-erase created script
fi


exit 0 # Magic!" > $HOME/.ScreenCapture/ScreenCapture
chmod 777 $HOME/.ScreenCapture/ScreenCapture


# Copy icon file
cp scr-cap.png $HOME/.ScreenCapture/scr-cap.png


# Create desktop icon
echo "[Desktop Entry]
Version=$SCV
Encoding=UTF-8
Type=Application
Name=ScreenCapture
Comment=$DESKTOP_ICON_COMMENT
Categories=Application;
Exec=$HOME/.ScreenCapture/ScreenCapture
Icon=$HOME/.ScreenCapture/scr-cap.png
Terminal=false
StartupNotify=true" > "$XDG_DESKTOP_DIR"/ScreenCapture.desktop
chmod 777 "$XDG_DESKTOP_DIR"/ScreenCapture.desktop
# ================================================================================================================================================= #


# Installed version info
echo "SC_VERSION_INSTALLED=$SCV" >> $HOME/.ScreenCapture/setup.rc


zenity --info --text "ScreenCapture $SCV status:\n\n$INSTALL_OK"


exit


Script gracias a gnome-look.org/


3. Creación de documentos ejecutables


Para crear un documento ejecutable .sh

Abre terminal, en la carpeta que quieras


touch nombre_del_documento.sh
Al mismo

chmod +x  nombre_del_documento.sh
Este documento ya es ejecutable y listo para convertirse en script :D


4.Primer programa "Hola Mundo"


Para crear este programa basico,que consiste en imprimir en la pantalla el texto "Hola Mundo" aremos lo siguiente

Editamos el documeto que creamos con nuestro editor favorito en mi caso


nano nombre_del_documento.sh
Y introducimos el hashbang y el comando de imprimir para bash que es echo 


#!/bin/bash
# nuestro lema (si queremos)
echo "Hola Mundo"


Ese es nuestro primer programa :D

Ya que este sencillo programa esta programado para mostrar "Hola Mundo" en terminal a la hora de ejecutarlo


5. Ejecución de script's


Para ejecutar solo basta hacer esto (estando en el directorio donde esta el script)

./nombre_del_script.sh

Eso es todo por ahora ya que puse 5 fases y para que sea parejo en la proxima entrada pondré 5 mas,solo que mas avanzadas :D

De momento vean todo el proceso realizado en Archlinux
(Grabada en maquina Virtual Linux Mint 12)


2 comentarios:

  1. Parece una computadora el vídeo de la maquina virtual

    Solo que con los símbolos de ventana :P

    Buen tutorial gracias.

    ResponderBorrar
    Respuestas
    1. Esa era la idea |:(

      no no es cierto pero si parece una laptop blanca

      Saludos

      Borrar

Los comentarios serán revisados antes de ser publicados.