bash

Mar 18 14:14

SPANISH: Lanzar un túnel ssh en background / ENGLISH: launch ssh tunnel in background

<p>SPANISH: Puede que a veces podamos necesitar crear un t&uacute;nel y dejarlo funcionando como si se tratase de un servicio cualquiera, pero por defecto, el cliente de 'ssh' no se lanza correctamente usando el m&eacute;todo com&uacute;n de usar '&amp;' y tampoco se lanza correctamente cuando lo colocas en un script de systemvinit/upstart. En estos casos, podemos usar estas opciones para lanzarlo: '-f -N' Se recomienda el uso de autenticaci&oacute;n por certificados, ya que de otra manera nos pedir&iacute;a el password y no ser&iacute;a muy &uacute;til :P Concretamente, el ejemplo que expongo lo he usado esto para hacer un mapeo de puertos desde un VirtualBox (hierro) y una VM alojada y conectada en &eacute;l por NAT :] Esta conexi&oacute;n se hac&iacute;a desde la VM al hierro.</p> <p>ENGLISH: Sometimes we may need create a tunnel and leave it running in background as if it were any other service, but 'ssh' client by default does not forks into background well using the common '&amp;' and it is not forked neither when you try to launch it via systemvinit/upstart script. In these cases, we can use this arguments to launch it into background: '-f -N'. It is recommended to use certs to authenticate with the foreign host, since in other way, it will prompt us for password and wouldn't be too useful as service :P I have used this to setup a NAT port forwarding between a VirtualBox host and a VM :]</p>
# ENGLISH: # # ssh -f -N -R LISTEN_PORT:localhost:22 user@REMOTE_HOST # # SPANISH: # # ssh -f -N -R PUERTO_DE_ESCUCHA:localhost:22 user@HOST_REMOTO # ssh -f -N -R 2232:localhost:22 distromatic@10.0.2.2
Lenguaje: 
bash
Sep 01 07:42

Comparar versiones de paquetes Debian / Debian package version comparison

* ESPAÑOL/SPANISH * Más de una vez se nos plantea la duda de si un paquete Debian que contiene en su versión caracteres como '+', '-' o '~' es de mayor versión que otro con unaversión similar. Para esto, podemos usar este sencillo comando que nos responderá en consecuencia lo que "dpkg" piensa :] Esto nos será mucho más ágil que recurrir a mirar la Debian policy (aunque nunca está de más saber qué es que) :P * ENGLISH/INGLÉS * Sometimes, when we find a Debian package which version contains special characters like '+', '-' or '~' we may wonder what version between two packages having similar versions is greater. For this case, we can use this easy command which will return what "dpkg" thinks about :] This will be much more easier than take a look to the Debian policy (although, it will never be a bad thing to do just to know what is what :P)
# Literalmente significa:
# "es '2.4~jaunty1' mayor que '2.4'?"
# Y si la respuesta es si, este comando nos devolverá "TRUE"
dpkg --compare-versions 2.4~jaunty1 gt 2.4 && echo TRUE
 
# Literally it means:
# "is '2.4~jaunty1' greater than '2.4'?"
# And if the answer from dpkg is afirmative, it will returno "TRUE"
dpkg --compare-versions 2.4~jaunty1 gt 2.4 && echo TRUE
Lenguaje: 
bash
Jun 26 21:07

Operaciones aritmeticas en bash

Las formas más conocidas para realizar operaciones aritméticas con bash son mediante let y expr. Todos sabemos que son un poco "pijoteras" en cuanto a sintaxis. El otro día trasteando por ahí encontré una forma a mi juicio bastante más sencilla.
# Forma tradicional con let
CONTADOR=0
while [ $CONTADOR -lt 10 ]; do
    echo "Contador vale: $CONTADOR"
    let "CONTADOR += 1"
done
 
# Con expr
CONTADOR=0
while [ $CONTADOR -lt 10 ]; do
   echo "$CONTADOR"
   CONTADOR=$(expr $CONTADOR + 1)
done
 
# Forma alternativa
CONTADOR=0
while [ $CONTADOR -lt 10 ]; do
   echo "$CONTADOR"
   CONTADOR=$((CONTADOR + 1))
done
 
# Esta última forma, permite usar o no usar dentro de la expresión '$' para la variable, 
# También se puede poner sin espacios, es decir, esto también lo ejecutará
 
...
CONTADOR=$(($CONTADOR+1))
...
 
# Po
Lenguaje: 
bash
Jun 07 19:39

Cambiar extensiones de fichero masivamente / Massive file extension renaming

-- Español / Spanish -- Seguro que más de una vez se nos ha dado el caso de tener que cambiarle la extensión a varios ficheros, para esto, yo siempre suelo usar este scriptcillo de una linea que aprovecha las extensiones de BASH. -- Inglés / English -- It's for sure that you have had to change the extension of various files anytime, for this matter, I always use this one-line-script taking advantages of BASH.
# ${file%.*} elimina todo desde el primer "." hasta el final, se podrían usar patrones como ".png" para hacer más exacta la coincidencia.<br />
for file in PATH/*.png; do mv $file ${file%.*}.jpg; done
Lenguaje: 
bash
Abr 03 02:19

Recodificar la codificación de carácteres de un fichero desde la CLI / Recode files char codification from CLI

* ENGLISH / INGLÉS * Sometimes we find some files (bash scripts, python code, or a simply plain-text file) which does not have the charset we expect and we need to easily recode it from command line. For this issues, we can use 2 tools which I usually forget: iconv and recode. This last one, does not come installed by default (iconv comes with libc6) and we'll have to install it (apt-get install recode). I'll give some examples below :] * SPANISH / ESPAÑOL * Algunas veces nos encontramos con algún fichero bien sea un script en bash, un python o un simple fichero de texto que no tiene la codificación deseada y necesitamos cambiarla desde la consola, para esto podemos usar 2 utilidades cuyos nombres habitualmente olvido: iconv y recode. Este &uacute;ltimo no viene instalado por defecto en el sistema (iconv viene con libc6) y habremos de instalarlo (apt-get install recode). A continuación un par de ejemplos :]
# list iconv supported charsets / listar codificaciones soportadas
iconv -l
# recode a file / convertir un fichero a una codificación con iconv
iconv -t UTF-8 file.txt -o output-file
 
# TODO: recode explanation :]
Lenguaje: 
bash
Abr 03 02:12

Recodificar la codificación de carácteres de un fichero desde la CLI / Recode files char codification from CLI

* ENGLISH / INGLÉS * Sometimes we find some files (bash scripts, python code, or a simply plain-text file) which does not have the charset we expect and we need to easily recode it from command line. For this issues, we can use 2 tools which I usually forget: iconv and recode. This last one, does not come installed by default (iconv comes with libc6) and we'll have to install it (apt-get install recode). I'll give some examples below :] * SPANISH / ESPAÑOL * Algunas veces nos encontramos con algún fichero bien sea un script en bash, un python o un simple fichero de texto que no tiene la codificación deseada y necesitamos cambiarla desde la consola, para esto podemos usar 2 utilidades cuyos nombres habitualmente olvido: iconv y recode. Este último no viene instalado por defecto en el sistema (iconv viene con libc6) y habremos de instalarlo (apt-get install recode). A continuación un par de ejemplos :]
# list iconv supported charsets / listar codificaciones soportadas
iconv -l
# recode a file / convertir un fichero a una codificación con iconv
iconv -t UTF-8 file.txt -o file
 
# TODO: recode explanation :]
Lenguaje: 
bash
Mar 30 08:51

What process a window belongs to?

Windows managers add some properties to windows and one of them is '_NET_WM_PID(CARDINAL)' which stores what PID created that window. In order to get that PID, we just have to execute the command below and click on the window we want to read info from :]
$ xprop |grep WM_PID
_NET_WM_PID(CARDINAL) = 2717
$ ps ax | grep firefox
2717 ?        Sl   387:39 /usr/lib/firefox-3.0.6/firefox
Lenguaje: 
bash
Mar 23 19:22

Releer tabla de particiones de un disco sin reiniciar

A petición de cerratillo, aquí tenéis este snippet que aunque a veces no es suficiente, muchas otras si:
sfdisk -R
Lenguaje: 
bash
Feb 09 17:49

rsync-over-ssh advanced use

If you want to make rsync-over-ssh to use specific 'ssh' options like, using a different identity key than the default one, you can use the '-e' rsync argument to pass options to the ssh command. Example above :]
# make rsync to use '/root/.ssh/non-bugged-id_rsa' to authenticate against the foreign host
#
rsync -avuz -e 'ssh -i /root/.ssh/non-bugged-id_rsa' remoteUser@remoteHost:/path /backup/path
Lenguaje: 
bash
Ene 14 16:25

Recuperar el 'exit code' de un comando "empipado" (filtrado por un 'pipe')

Cuando "empipas" un comando y recuperas el exit code de la forma habitual ($?), recuperas el exit code del comando a la derecha del pipe. Alguna vez nos podría ser necesario recuperar el exit code del comando a la izquierda y esto se hace mediante la variable $PIPESTATUS. Un ejemplo practico a continuación :]
# comprobamos que $? devuelve la salida del grep
# '0' significa que grep encontró la cadena
~$ sudo apt-get install DUMMY | grep estado
Leyendo la información de estado...
E: No se pudo encontrar el paquete DUMMY
~$ echo $?
0
~$
 
# aquí comprobamos que 100 es lo que devuelve apt
~$ sudo apt-get install DUMMY
Leyendo lista de paquetes... Hecho
Creando árbol de dependencias
Leyendo la información de estado...
Lenguaje: 
bash