Guida utilissima per lo script di shell
Esempi utili di script
Diversi modi di lanciare uno script
sorgente http://unix.stackexchange.com/questions/2976/different-ways-to-execute-a-shell-script
. script # using the . (dot)
source script # using the `source` command
It executes the script in-place (as if you copied and pasted the script right there). This means that any functions and non-local variables in the script remain. It also means if the script does a cd into a directory, you'll still be there when its done.
Funzioni con parametri e valori di ritorno
http://tldp.org/LDP/abs/html/complexfunct.html
http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-8.html
#!/bin/bash
# Functions and parameters
func1() {
#echo "1" $1 "2" $2
rep=`echo $1$2`
}
func1 peppe ciao
echo $rep
func1 ciao peppe
echo $rep
Eseguire uno script in modalita' debug
sempre http://unix.stackexchange.com/questions/2976/different-ways-to-execute-a-shell-script
bash -x ~/bin/ducks
SCRIPT UTILI CHE HO USATO
multi if
http://www.freeos.com/guides/lsst/ch03sec04.html
!/bin/sh
# Script to test if..elif...else
#
if [ $1 -gt 0 ]; then
echo "$1 is positive"
elif [ $1 -lt 0 ]
then
echo "$1 is negative"
elif [ $1 -eq 0 ]
then
echo "$1 is zero"
else
echo "Opps! $1 is not number, give number"
fi
Name Parsing extract filename
elaborate file name from http://stackoverflow.com/questions/965053/extract-filename-and-extension-in-bash
~% FILE="example.tar.gz"
~% echo "${FILE%%.*}"
example
~% echo "${FILE%.*}"
example.tar
~% echo "${FILE#*.}"
tar.gz
~% echo "${FILE##*.}"
gz
Basename
Usually you already know the extension, so you might wish to use:
basename filename .extension
for example:
basename /path/to/dir/filename.txt .txt
and we get
filename
FOR
Questo script usa il for per cercare un testo dentro le librerie jar presenti nella cartella dove si lancia. Sostituire la stringa jayasoft con quello che si vuole cercare
for lib in $(ls ./*); do jar tf $lib | grep "jayasoft";echo "--^ $lib ";done
Lo stesso codice in modo più leggibile disposto su più righe
for lib in $(ls ./*);
do
jar tf $lib | grep "jayasoft";
echo "--^ $lib ";
done
Spieghiamolo:
cioè per ogni elemento nella cartella . trovato con ls fai il jar tf
fagli un grep sul contenuto del jar poi stampa il nome del file su cui è stato fatto il grep
grandioso
Elimina tutte le cartelle .svn dentro la directory locale
for lib in $(find . -name .svn); do rm -rf $lib; done
WHILE e IF
#!/bin/sh
if [ $# -eq 0 ]
then
echo "Error - Number missing form command line argument"
echo "Syntax : $0 number"
echo " Use to print multiplication table for given number"
exit 1
fi
i=1
while [ $i -le 10 ]
do
echo $i
i=`expr $i + 1`
wget localhost:8080
sleep 2
done
RIAVVIO AUTOMATICO DI UN TOMCAT CHE POTREBBE ANCHE ESSERE BLOCCATO
Non si può usare il semplice shutdown.sh perchè nel caso il tomcat fosse bloccato non si spegnerebbe. In questo modo invece si recupera il pid, si killa brutalmente, si aspetta 5 secondi e si riparte.
Il tutto può essere fatto partire da /etc/crontab
PIDTOKILL=`ps aux | grep qualcosa | grep java | awk '{print $2}'`
echo $PIDTOKILL
kill -9 $PIDTOKILL
sleep 5
/opt/tomcat/bin/startup.sh
TROVARE LE CARTELLE VUOTE
Mi è capitato di dover cercare cartelle che non contenevano file in un albero molto grande.
Ho usato questi due comandi
find . -type d >> lista.txt
du -h < lista.txt | grep "4,0K" >> dir.txt
- con il comando find ottengo una lista di directory che metto in un file
- dopo di che con il comando du per ogni cartella calcolo la dimensione, le cartelle che non hanno file o altre cartelle dentro avranno una dimensione pari a quella dell'inode che dipende dal s.o. però di solito è 4 K
- quindi filtro per questo valore e metto il risultato dentro dir.txt
Linux Shell Scripting Tutorial
Chapter 2: Getting started with Shell Programming
How to write shell script
Ecco un primo script
#
# Script to print user information who currently login , current date & time
#
clear
echo "Hello $USER"
echo "Today is \c ";date
echo "Number of user login : \c" ; who | wc -l
echo "Calendar"
cal
exit 0
Stampa il nome utente, la data di oggi
Il numero di utenti loggati , who stampa le righe degli utenti (da capire meglio nel dettaglio), wc -l le conta
Variables in Shell
Le variabili di shell stanno in ram
Ci sono due tipi di variabili quelle di sistema, e quelle dell'utente UDV user defined variable.
Si possono settare le variabili dando un comando tipo $ set ecco un elenco delle più importanti:
System Variable Meaning
BASH=/bin/bash Our shell name
BASH_VERSION=1.14.7(1) Our shell version name
COLUMNS=80 No. of columns for our screen
HOME=/home/vivek Our home directory
LINES=25 No. of columns for our screen
LOGNAME=students students Our logging name
OSTYPE=Linux Our Os type
PATH=/usr/bin:/sbin:/bin:/usr/sbin Our path settings
PS1=[\u@\h \W]\$ Our prompt settings
PWD=/home/students/Common Our current working directory
SHELL=/bin/bash Our shell name
USERNAME=vivek User name who is currently login to this PC
Per stampare il contenuto di una var
$ echo $USERNAME
$ echo $HOME
Echo command
echo [options] [string, variables…]
Options
-n scrive senza mettere il new line alla fine
-e abilita i seguenti metacaratteri che altrimenti non funzionerebbero:
\a alert (bell)
\b backspace
\c suppress trailing new line
\n new line
\r carriage return
\t horizontal tab
\\ backslash
Shell Arithmetic
$ expr 1 + 3
$ expr 2 - 1
$ expr 10 / 2
$ expr 20 % 3
$ expr 10 \* 3
$ echo `expr 6 + 3`
More about Quotes
" Double Quotes "Double Quotes" - Anything enclose in double quotes removed meaning of that characters (except \ and $).
' Single quotes 'Single quotes' - Enclosed in single quotes remains unchanged.
` Back quote `Back quote` - To execute command
Example:
$ echo "Today is date"
Can't print message with today's date.
$ echo "Today is `date`".
Nel secondo caso esegue il comando date
Exit status
To determine this exit Status you can use $? special variable of shell.
For e.g. (This example assumes that unknow1file doest not exist on your hard drive)
$ rm unknow1file
It will show error as follows
rm: cannot remove ‘unkowm1file’: No such file or directory
and after that if you give command
$ echo $?
it will print nonzero value to indicate error. Now give command
$ ls
$ echo $?
It will print 0 to indicate command is successful.
The read Statement
Leggere un valore da tastiera
echo "Your first name please:"
read fname
echo "Hello $fname, Lets be friend!"
read variabile1, variabile2, …., variabileN
Wild cards (Filename Shorthand or meta Characters)
- caratteri jolly multipli
- ? carattere jolly singolo
- [abc]* stringa specifica che inizia con abc
- [a-c]* con il - si intende un range quindi matcha tutto quello che inizia con la lettera a b o c
- [!a-d]* oppure [^a-d] range che non matcha
$ ls /bin/[^a-o]
To stop all process except your shell
kill 0
To get information about all running process
ps -ag
Chapter 3: Shells (bash) structured Language Constructs
if condition
Questo file esegue il cat se
$ cat > showfile
#!/bin/sh
#
#Script to print file
#
if cat $1
then
echo -e "\n\nFile $1, found and successfully echoed"
fi
un altro script usato da me per il backup
#!/bin/sh
#
# decidiamo se lanciare lo script per il mese o l'anno
#
if test $1 = "giornaliero"
then
echo "backup giornaliero"
/root/bin/db/liferay-settimanale
/root/bin/files/liferay-settimanale
fi
if test $1 = "mensile"
then
echo "backup mensile"
/root/bin/db/liferay-mensile
/root/bin/files/liferay-mensile
fi
in questa pagina http://www.freeos.com/guides/lsst/ch03sec02.html vi sono tutte le opzioni per usare l'if in maniera avanzata
awk
Ecco un esempio di utilizzo di awk
echo `vmstat | awk '{ if ( $1 == "procs" || $1 == "r" ) { } else {print $0 date } }' ` `date` >> /root/logs/macchina.log
il vmstat stampa tre righe lui con quell'if esclude la prima che comincia per procs e la seconda che cominica con r e scrive solo i valori numerici della terza riga sul file di log. In più gli concatena anche un date per sapere in che time è stata fatta la rivelazione.
check if a directory is empty
[ "$(ls -A /path/to/directory)" ] && echo "Not Empty" || echo "Empty"
remove the -A if for you the hidden files are not relevant