Posts Tagged ‘tips’

bash scripting: change delim using for

gennaio 7, 2013 Commenti disabilitati

Usually when I write shell script I prefer to use the statement “for”.
But there’s a problem: by default the ‘for’ get every single word.

That’s because if not specified the ‘for’ use as delimiter the space character (” “).
So, if I want to work with several word in a single iteration i need to change the delimiter.

That’s easy!
To change the delimiter you just need to change the variable IFS.

Let’s see some code:

IFS=";"                              # change delimiter in ";" (magic)
EXCEPTIONS="timeout;java.somerror;a lot of errors"    # my exception 
for word in $EXCEPTIONS;do
    echo -n "Check Exception: \"$word\" ..."         # escape "
    N=$(grep -ic $word $LOGFILE)                     # check log
    if [ $N -gt 0 ];then                             # if found
        echo -e "\nWARNING: Found $N exception:\"$word\"" # print 
        echo "None"                                  # else no


> Check Exception: "timeout"...None
> Check Exception: "java.somerror"...None
> Check Exception: "a lot of errors"...
WARNING: Found 3 exception "a lot of errors"

That’s an easy way to use the ‘for’ statement even if usually cant and so you can write good code.
enjoy 🙂

Categorie:linux Tag:, , , , , , ,

edit a string in multiple files: sed -ic

ottobre 19, 2012 1 commento

Sed is a great tool used to edit one line if needed for multiple files without open it.
Usually to do this, you just need to:

1. Looking for the right regular expression:

grep -re “user” /my/dir

2. Inject the update string

sed -ic ‘s/user/newuser/g’ <filename>

3. Enjoy!


WARNING : the option “-c” is needed to preservate the owner of the file, if not set the file change permission with the actual owner.

Categorie:linux Tag:, , , ,


ottobre 19, 2012 Commenti disabilitati

Trucchetti in bash:

In Linux con coreutils >= 7.0 è possibile lanciare il comando timeout da commandline,

timeout 1 sleep 1000

Ad esempio per lanciare un tcpdump per 10 secondi possiamo scrivere:

timeout 10 sudo tcpdump -ni eth0 -w /tmp/test.pcap


Categorie:linux Tag:, , ,

tip to restore del file

luglio 15, 2009 Commenti disabilitati
C'è un modo per recuperare al volo un file che si stava usando e si è cancellato per sbaglio:

1. open with less command your file
   $  less testfile.txt

2. open another terminal and remove it
   $  rm testfile.txt
Ora in teoria sei fottuto, il file è cancellato infatti:
   $ ls testfile.txt
   ls: testfile.txt: No such file or directory

Ma noi abbiamo ancore un less aperto per quel file, quindi:

3. lsof | grep testfile.txt

less	4607	samba  4r  REG 254,4   21  8880214 /home/samba/testing.txt (deleted)
        ^^^^           ^^^
Dalla seconda e quarta colonna ottengo le informazioni necessarie per ripristinare il file:

   $ cp /proc/4607/fd/4 testing.txt.bk

ps: attenzione a non usare l'opzione cp -a , che lo copia come link simbolico.

Categorie:varie Tag:, , , ,