Showing posts with label Unix. Show all posts
Showing posts with label Unix. Show all posts

Friday, October 19, 2012

shell clipboard

Ever wanted to cut something from the shell?
Do you need to paste some information stored in a file into your web browser, but you are too lazy to fire up your text editor, select, and hit ctrl+c?
Are you a shell enthusiast?

Than xclip(1) is good for you. It's a CLI to X clipboard, which lets you store into the clipboard buffer what you type on stdin, or from a file.

But to simplify more the task of cutting and pasting, you can create (if you are using, for example, bash) a simple alias in your .bashrc file like this one:

alias clipboard="xclip -i -selection clipboard"

Then, you can simply copy a file in the clipboard like:

$ cat file | clipboard

or directly write in it:


$ clipboard 
hi, how are you?
CTRL+D

And your productivity will be maximized for sure!!!



Thursday, September 6, 2012

Bash Shell Calculator

Working on the Linux shell has always missed something, in my experience: an easy-to-use calculator.

Yes, there is the almighty bc, but it is everything but immediate to use. So here I'm just sharing an easy to implement wrapper to bc, which allows to easily use your shell as a calculator.

Simply drop these lines into a file called 'calc':


#!/bin/bash
echo "scale=2; $1" | bc; exit

Then simply make it executable and copy it into /usr/bin/:

$ chmod 755 calc
# mv calc /usr/bin


Then, you can start doing your math in your shell, simply like:

$calc 3/2
1.50

Consider that, if you want to use more complex operations, you have to escape any special character, like:

$ calc \(3+2\)/4
1.25

And simply change the number after "scale=" to add more precision to the results!

Wednesday, June 6, 2012

diff e patch in dieci minuti

Prima situazione: stai cercando di compilare un pacchetto dai sorgenti e scopri che qualcuno ha già fatto il lavoro per te, modificandolo un po' per farlo compilare sul tuo sistema. Il suo lavoro è disponibile come "patch", ma non sei sicuro di come si fa ad utilizzarlo. La risposta è che puoi applicare la patch ai sorgenti originali con un comando chiamato, appropriatamente, patch.

Seconda situazione: hai scaricato i sorgenti di un pacchetto open source e dopo un'oretta di piccoli cambiamenti, riesci a compilarlo sul tuo sistema. Vorresti rendere il tuo lavoro disponibile agli altri programmatori, oppure agli autori del pacchetto, senza dover ridistribuire tutto quanto il pacchetto modificato. Ti trovi quindi in una situazione in cui devi creare da te una patch, e lo strumento necessario è diff.

Questa è una breve guida a diff e patch, che ti aiuterà in queste situazioni descrivendo questi strumenti e come vengono utilizzati nella maniera più comune. Ti dirà abbastanza per cominciare ad utilizzarli subito. Dopo, potrai imparare da te i vari comandi aggiuntivi per il tuo piacere personale, utilizzando le pagine del manuale.

Applicare una patch con patch

Per applicare una patch ad un singolo file, spostati nella cartella dove è situato il file ed invoca patch:

patch < foo.patch

Queste istruzioni assumono che la patch sia distribuita in un formato unificato, che identifica il file al quale si deve applicare la patch. Se non è questo il caso, si può specificare il file da riga di comando:

patch foo.txt < bar.patch

Applicare delle patch ad intere cartelle (forse il caso più comune) è simile, ma si deve fare attenzione a specificare un "livello p". Questo vuol dire che, all'interno dei file di patch, i file cui applicare la patch sono identificati da percorsi che possono essere diversi ora che i file sono situati sul tuo computer, piuttosto che su quello in cui la patch è stata creata. Il livello p dice a patch di ignorare porzioni del percorso ai file, così da poterli identificare in maniera corretta. Nella maggior parte dei casi un livello p corrispondente a uno funziona, quindi si può usare:

patch -p1 < baz.patch

Ti dovresti spostare nella cartella principale dei sorgenti prima di lanciare questo comando. Se il livello uno non identifica correttamente nessun file cui applicare la patch, verifica il contenuto del file di patch per controllare i nomi dei file. Se trovi un nome del tipo:

/users/stephen/package/src/net/http.c

e stai lavorando nella cartella che contiene net/http.c, usa:

patch -p5 < baz.patch

In generale, aggiungi uno per ciascun separatore di cartella (la barra '/') che vuoi rimuovere dall'inizio del percorso, fino a che quello che resta è un percorso che esiste nella tua cartella di lavoro. Il valore che raggiungi, è il corrello livello p.

Per rimuovere una patch, utilizza il flag -R, ad esempio:

patch -p5 -R < baz.patch

Creare delle patch con diff

Utilizzare diff è molto semplice, sia che si stia lavorando con singoli file, sia che si stia lavorando su intere cartelle. Per creare una patch per un solo file, usa la forma:

diff -u original.c new.c > original.patch

Per creare una patch per un intero albero di cartelle, fanne una copia:

cp -R original new

Applica tutte le modifiche che intendi fare nella cartella new/. Dopo crea un file di patch con il seguente comando:

diff -rupN original/ new/ > original.patch

Questo è tutto quello che serve per incominciare ad usare diff e patch. Per altre informazioni, puoi sempre usare:

man diff
man patch


Freely translated from this original post, for my own convenience.

Friday, May 11, 2012

Record audio output

So, here's the story. We live in a web-radio era / audio-streaming world.
The old-days audiotape is no longer helpful in recording sounds around us.

Thus, after some headache, this is my modern "Linux audiotape", which I use to record.

Basically, it relies on pulseaudio (I'm running alsa with pulseaudio on my arch distro).
In particular, this script queries pulseaudio to know which is the first audio sink installed in the system (that is, the first audio source that is currently being directed to the output soundcard) and creates a dummy sink which is used to take the output and redirect it into a file.

Then, since we do not want to fill up our disk with raw pcm directed to the speakers, the signal is pipe'd into an ogg encoder, which silently compresses our data and stores it into disk.

#!/bin/bash

sinksIndex=`echo list-sink-inputs | pacmd | grep index | head -1 | sed 's/^.*index:\s\([0-9]\+\).*$/\1 /'` # Get wanted index

echo "Recording to audioRecord.ogg... CTRL+C to stop."

pactl load-module module-null-sink sink_name=audioRecord
pactl move-sink-input $sinksIndex audioRecord
parec -d audioRecord.monitor | oggenc -b 192 -o audioRecord.ogg --raw -

The only important thing to consider, is that to record exactly what we mean to, we must stop any audio stream in the system, start the one which we want to grab, and then launch this script.

This will work with youtube, webradios, audio streaming services, and so long and so forth. To restore the audio setting, after the recording is over, you must restart pulseadio with:

pulseaudio --kill

And furthermore, the program which was generating must be restarted as well. Otherwise, no sound will be heard from your machine.

And by the way, if you want to hear what's going on in your recording, you can just launch something like 'vlc audioRecord.ogg': it will play you the recording while it's still writing the file! (thank you, Unix File System!)

Thursday, May 10, 2012

Check for logged users

At office, we have a cluster made of several machines used for performance experiments. We are not a lot of people, so we explicitly avoided installing software for launching experiments in a controlled way.

Nevertheless, seldom happens that someone remotely logs in and launches stuff, without noticing, for example, if other users were logged or where running programs, thus invalidating any output from (long) runs.

So, at last, I wrote the following bash script which, upon ssh login to the servers, outputs a fancy colored message telling that someone else is logged in (if any).

#!/bin/bash

#for user in $(last | grep still | sort | uniq);
ME=`whoami`



for user in $(last -Rw | grep still | sed 's/ .*//' | sort | uniq);
do
        if [ "$ME" != "$user" ]
        then
                echo -en '\E[;31m'"\033[1mWARNING:\033[0m"   # Red
                echo -en '\E[;34m'"\033[1m \033[4m$user\033[0m \033[0m"
                tput sgr0
                echo -n "still logged in since "
                echo `last -RFw | grep $user | head -1 | awk '{print $4" "$5" "$6}'`
        fi
done

I've simply added this script to /etc/bash.bashrc, so that every user gets a warning message, if needed.

Monday, October 31, 2011

Multithread Barrier (yes, it's a join!)

This post doesn't want to clearify all aspects of parallel programming. It's just an example to show how you have to thinkg when writing parallel code!

When you deal with concurrent programming, everything is going to be screwed up very easily. Debugging is a pain in the ass, and every one who has ever written a multithreaded software, although very simple as a concurrent server, has experimented with such a pain.

One fundamental operation in multithreaded programs is synchronization. In particular, one operation which I consider very important is a thread barrier, that is a line of code in the program which guarantees that if a thread is executing before it, no one else is executing after it, and if there is some thread after it, then every other thread is, at least, executing that line, but not anything before...

Monday, April 11, 2011

Sei modi per mandare Linux in crash. Perché è divertente ed inutile!

Questo è uno di quei post assolutamente senza senso, ma che mi piacciono. È come giocare alla WII: non ha senso, ma ti (ci) piace!
Qui di seguito ci sono alcuni modi per mandare in crash un sistema Unix. Alcuni di essi sono ben conosciuti, come la Fork Bomb, altri sono più oscuri. Alcuni sono irreversibili, altri invece durano soltanto "una sessione", e dopo un bel riavvio tutti gli effetti sono spariti.


  • La Fork Bomb: è un classico che non può essere omesso da questo elenco. In effetti, gli viene dedicata persino un'intera pagina su Wikipedia!
     :(){ :|: & };:
    Questo comando, incollato in una shell, farà terminare alla macchina tutte quante le risorse, a meno che il numero di processi per utente non venga limitato in /etc/security/limits.conf.
  • Il comando seguente sovrascriverà l'MBR com dati (pseudo) casuali. In questo modo, si potrà essere sicuri che la propria macchina non riparta più (no, neppure con Windows).
    dd if=/dev/urandom of=/dev/sda bs=512 count=1
  • Leggere dalle porte di I/O può avere dei simpatici effetti secondari. Provate ad eseguire questo comando, e capirete quello di cui sto parlando:
    sudo less -f /dev/port
    Il risultato sarà che la vostra macchina si inchioderà. Non ho ancora approfondito il motivo alle spalle di questo fenomeno, ma è comunque divertente!
  • Cosa succede se la memoria di un processo viene sovrascritta? Di solito, ci si imbatte in un segfault. Si può infilare un po' di divertimento (casino!) nella memoria di sistema:
    cp /dev/zero /dev/mem
  • Quest'ultimo è diventato un cult, dal momento che un sacco di gente ci si è imbattuta (forse anche tu). In qualche modo si fa confusione, e si rimuove ogni singolo file dal disco rigido
    rm -rf /*


In ultimo, si può utilizzare il potere del comando 'find', con l'argomento 'exec' che eseguirà il comando scritto immediatamente dopo. Questo è esattamente quello che può capitare quando si va di fretta.
find . -type f -name * -exec rm -f {} \;
Per fortuna, molti di questi comandi (eccezion fatta per la Fork Bomb), non danneggeranno il vostro computer se lanciati come utenti senza privilegi di amministratore, perché il sistema non vi lascerà accedere a file per i quali non avete i permessi.
Ovviamente, se si prova a scrivere qualche modulo del kernel, è molto probabile che esso vada in crash con la vostra approvazione! :) A quel punto, qualsiasi cosa è possibile, perché sarete diventati l'"Onnipotente"!

Wednesday, March 9, 2011

Showing a Tree

In these GUIful days, where everything we do on a computer involves using the mouse pointer, sometimes there comes situations where we want an old-fashioned visualization of data.

For example, in these days I'm working hard on the restyling of an application which be released soon. This entails cutting old functions, adding comments, rewriting Makefiles, and rearranging the directory tree. Yes, the boring part off programming.

For easiness, I decided to print the whole directory tree listing of my project, to better visualize the changes I have to apply to my project. Thus, before coming into tree(1) I opted for the hard-coded solution, and produced this command:
ls -R | grep ":" | sed -e 's/://' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'
Which will draw the currents' directory tree listing. Surely, using tree is much easier and more efficient, but this old-fashioned approach is what I like most!