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
Dic 01 16:51

Forzar apt a usar una "arch" determinada

Si queremos que apt busque en unos repositorios paquetes de una arquitectura diferente a sobre la que fue compilado.
# para hacerlo desde la CLI directamente
apt-get update -o APT::Architecture=i386
 
# para meterlo en un fichero de configuración permanente:
echo 'APT::Architecture "i386";' >> /etc/apt/apt.conf.d/99setarch
Lenguaje: 
bash