Sie sind auf Seite 1von 41

# Programao Profissional Shell Script

Neste treinamento Hands-on vamos trabalhar com os


principais recursos do Shell para automatizar nossa
atividades administrativas no ambiente.

Pontos Importantes
01. Este treinamento parte do principio que voc j possui
conhecimento dos principais comandos bsicos do Shell
"Bash" e possui total capacidade de assimilar os novos
comandos que sero apresentados em nosso treinamento.
02. Nosso objetivo no de desenvolver sistemas e sim
automatizar diversas atividades utilizando esta ferramenta.
03. Utilizaremos neste treianmento toda fundamentao da
"Lgica de Programao" para desenvolver nossos scripts.

Bash
- Voc j conhece a maioria dos comandos utilizados para
consulta e manipulao de dados do Shell Bash. No
entanto, vamos falar de alguns pontos bsicos importantes.

Variveis de Ambiente.
A definio mais simples para uma varivel de
ambiente "Um elemento que armazena uma informao".
Existem diversas maneiras de armazenar esta
informao nas variveis de ambiente no Linux:

:: Uma simples varivel


[wig@notewig /]$ eu=wigberto
[wig@notewig /]$ echo $eu
wigberto
[wig@notewig /]$

:: Armazenando a sada de um comando


[wig@notewig /]$ DATE=$(date)
[wig@notewig /]$ echo $DATE
Seg Mar 8 21:15:07 BRT 2010
[wig@notewig /]$

:: Variveis Comuns
[wig@notewig /]$ echo $HOME
/home/wig
[wig@notewig /]$ echo $PWD
/
[wig@notewig /]$ echo $HOSTNAME
notewig.local
[wig@notewig /]$ echo $LANG
pt_BR.UTF-8
[wig@notewig /]$ echo $USERNAME
wig
[wig@notewig /]$ echo $SHELL
/bin/bash
[wig@notewig /]$

:: Consultando Variveis
[wig@notewig /]$ env
ORBIT_SOCKETDIR=/tmp/orbit-wig
HOSTNAME=notewig.local
IMSETTINGS_INTEGRATE_DESKTOP=yes
TERM=xterm
SHELL=/bin/bash
XDG_SESSION_COOKIE=aaa7089dce0abc1e940d14964aca759b-1268091213.243468-1080613821
HISTSIZE=1000
GTK_RC_FILES=/etc/gtk/gtkrc:/home/wig/.gtkrc-1.2-gnome2
WINDOWID=75499625
QTDIR=/usr/lib64/qt-3.3
QTINC=/usr/lib64/qt-3.3/include
IMSETTINGS_MODULE=none
...
no_proxy=localhost,127.0.0.0/8
GNOME_DESKTOP_SESSION_ID=this-is-deprecated
LOGNAME=wig
QTLIB=/usr/lib64/qt-3.3/lib
CVS_RSH=ssh
DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbusNjGU72dd1t,guid=a99572eb5696e6290b73cc7d4b95894d
LESSOPEN=|/usr/bin/lesspipe.sh %s
DISPLAY=:0.0
G_BROKEN_FILENAMES=1
XAUTHORITY=/var/run/gdm/auth-for-wig-SCa6ft/database
COLORTERM=gnome-terminal
_=/usr/bin/env
[wig@notewig /]$

- Primeiro Script
#!/bin/bash
# hello.sh
echo Hello, este e o meu primeiro script.
# chmod +x hello.sh
# ./hello.sh

Entrada de Dados
#!/bin/bash
#input.sh
echo ":: informe o valor de entrada: "
read VALOR
# read -p ":: INFORME O VALOR DE ENTRADA: " VALOR
# read -t 5 VALOR #esta a entrada por 5 segundos
# read -n 10 VALOR #somente 10 caracteres
echo ":: o valor inserido foi: " $VALOR

Variveis e Atributos
Toda varivel Bash armazenada como string. Cada
varivel possui atributos, que podem ser convertidos
usando o comando declare.
Se uma varivel for declarada com -i (inteiro), o Bash
converte a varivel para um inteiro. Neste caso o Shell ir
lembrar que a varivel deve ser tratada como um inteiro.
Se um valor no numero for atribudo a varivel o Shell no
reporta um erro. Ao invs disso ser atribudo um valor
zero.

Declarando Inteiro
$ declare -i NUMBER_ACCOUNTS=15
$ printf %d\n $NUMBER_ACCOUNTS
15
$ NUMBER_ACCOUNTS=Smith # mistake
$ printf %d\n $NUMBER_ACCOUNTS
0
$ NUMBER_ACCOUNTS=12
$ printf %d\n $NUMBER_ACCOUNTS
12

Constantes
Para valores constantes podemos usar o atributo -r
(read-only). Se voc tentar atribuir um valor o Bash
reporta um erro.
$ declare -r COMPANY=Smith and Jones
$ printf %s\n $COMPANY
Smith and Jones
$ COMPANY=Wilson Distribution
bash: COMPANY: readonly variable

Arrays
Arrays so listas de valores criado no Bash com o
atributo -a (array). Um nmero chamado index referncia
para a posio do item no array. Um Array no Bash
diferente de um array em outras linguagens porque
possuem "tamanho aberto".
$ declare -a PRODUCTS
$ declare -a DEPT [0] = "contabilidade" DEPT [1]="Vendas"
DEPT[2]="Suporte"
$ echo "${ DEPT[0]}"
contabilidade
$ echo "${ DEPT[2]}"

Outros Exemplos
printf %s ${PRODUCTS[5]}
$ PRODUCTS[5]=hammers
$ printf %s ${PRODUCTS[5]}
hammers
$ PRODUCTS[0]=screwdrivers
$ printf %s $PRODUCTS
screwdrivers
$ printf %s ${PRODUCTS[0]}
screwdrivers

$ printf %s ${PRODUCTS[*]}
screwdrivers hammers
/home/kburtch [bash]
$ printf %s ${PRODUCTS[@]}
screwdrivershammers
$ printf %s %s\n ${PRODUCTS[@]}
screwdrivers hammers
$ DIVISIONS=(North America Europe Far East)
$ printf %s\n ${DIVISIONS[*]}
North America Europe Far East
$ DIVISIONS=([3]=North America [2]=Europe [1]=Far East)
$ printf %s\n ${DIVISIONS[*]}
Far East Europe North America

Exportando Variveis.
As variveis no Shell, seja em um script seja na forma
interativa, tem o escopo somente dentro do Shell. Estas
variveis podem ser exportadas, sendo assim, seu escopo
estar tambm fora do lugar de origem. Uma varivel pode
ser exportada com o atributo -x (export).
# outer.sh
#
# This script runs first.
declare -rx COMPANY_BRANCH=West Coast Branch
bash inner.sh
printf %s\n $COMPANY_BRANCH
exit 0

# inner.sh
#
# This script is run by outer.sh.
printf This is the inner script.\n
declare -p COMPANY_BRANCH
COMPANY_BRANCH=East Coast Branch
printf %s\n $COMPANY_BRANCH
printf Inner script finished\n
exit 0

Expresses
Uma expresso uma frmula para calcular um valor.
No Bash existem diversos comandos e funes para
computar expresses. Em alguns casos existem mais de
uma maneira de calcular a mesma expresso.

O comando IF
O comando if verifica um resultado.
Se o comando for bem sucedido o if executa outro
comando.
if <argumento de teste>; then
comando a ser executado
if
if test -f ./resultado.out; then
printf "O Arquivo resultado.out foi gerado com sucesso!\n"
if

Comando Test
O comando test pode realizar uma variedade de testes com o
arquivo:
-b file Verdadeiro se o arquivo um block device
-c file Verdadeiro se o arquivo um character device
-d file Verdadeiro se o arquivo um diretrio
-e file Verdadeiro se o arquivo existir
-f file Verdadeiro se o arquivo existir e for regular
-g file Verdadeiro se o arquivo possuir o GUID definido
-h file Verdadeiro se o arquivo for um link simblico
-k file Verdadeiro se o arquivo possuir o SUID definido.
-r file Verdadeiro se o arquivo for legvel para o script
-s file Verdadeiro se o arquivo no estiver vazio

-S file Verdadeiro se o arquivo for um socket


-u file Verdadeiro se o arquivo possuir o set-user-id
permission definido
-w file Verdadeiro se o script tiver permisso de escrita
-x file Verdadeiro se o script tiver permisso de execuo
-O file Verdadeiro se o arquivo tiver o proprietrio

usurio que esta executando o script.


-G file Verdadeiro se o arquivo tiver o grupo dono o mesmo
grupo do usurio que esta executando o script
f1 -nt f2 Verdadeiro se o arquivo f1 for mais recente que o
arquivo f2.

Verificao com Strings


-z - verdadeiro se a string estiver vazia
-n - verdadeiro se a string no estiver vazia
s1 = s2 - verdadeiro se s1 igual a s2
s1 != s2 - verdadeiro se s1 diferente de s2
s1 < s2 - verdadeiro se s2 menor que s2
s1 > s2 - verdadeiro se s1 maior que s2

DAY=`date+%a`
if[$DAY=Mon];then
printf...diadetrabalho!\n
if
DAY=`date+%a`
if[$DAY=Sato$DAY=Sun];then
WEEKEND=1
if

Expresses Aritmticas
O comando let utilizado para clculos matemticos:
$letSUM=5+5
$printf%d$SUM
10
$letRESULT=5+2
$printf5plus2is%d\n$RESULT
5plus2is7
$letRESULT=5*2
$printf5times2is%d\n$RESULT
5times2is10
$letRESULT=5/2
$printf5dividedby2is%d\n$RESULT
5dividedby2is2
$letRESULT=5%2
$printfremainderof5dividedby2is%d\n$RESULT
remainderof5dividedby2is1

OperadoressemelhantesaoC
,+Unaryminusandplus
!,~Logicalandbitwisenegation(disableshell
historytouse!)
*,/,% Multiplication,division,andremainder
+,Additionandsubtraction
<<,>Leftandrightbitwiseshifts
<=,>=,<,>Comparison
==,!=
Equalityandinequality
&BitwiseAND
^BitwiseXOR
|BitwiseOR
&&LogicalAND
||LogicalOR
expr?Expr: Conditionalexpression
=,*=,/=,%= Assignment
+=,=,<<=,>>=,&=,^=,|=Selfreferential
operations

Expresses Lgicas
$ let RESULT=!0
$ printf logical negation of 0 is %d\n $RESULT
logical negation of 0 is 1
$ let RESULT=!1
$ printf logical negation of 1 is %d\n $RESULT
logical negation of 1 is 0
$ let RESULT=1 && 0
$ printf logical and of 1 with 0 is %d\n $RESULT
logical and of 1 with 0 is 0
$ let RESULT=1 || 0
$ printf logical or of 1 with 0 is %d\n $RESULT
logical or of 1 with 0 is 1

Operadores Relacionais
$ let RESULT=1 > 0
$ printf 1 greater than 0 is %d\n $RESULT
1 greater than 0 is 1
$ let RESULT=1 >= 0
$ printf 1 greater than or equal to 0 is %d\n $RESULT
1 greater than or equal to 0 is 1
$ let RESULT=1 < 0
$ printf 1 less than 0 is %d\n $RESULT
1 less than 0 is 0
$ let RESULT=1 <= 0
$ printf 1 less than or equal to 0 is %d\n $RESULT
1 less than or equal to 0 is 0
$ let RESULT=1 == 0
$ printf 1 equal to 0 is %d\n $RESULT
1 equal to 0 is 0
$ let RESULT=1 != 0
$ printf 1 equal to 0 is %d\n $RESULT
1 equal to 0 is 1

Operadores Auto-Relacionais
$ let RESULT=5
$ let RESULT+=5
$ printf The result is %d $RESULT
The result is 10

Caso Especial
$ VALUE=5
$ let RESULT=VALUE > 1 ? 1 : 0
$ printf %d\n $VALUE
1

$ FILE_COUNT=`ls -1 | wc -l`
$ let RESULT=FILE_COUNT==0 ? 0 : (FILE_COUNT%2 == 0 ? \
FILE_COUNT/2 : FILE_COUNT/2+1)
$ printf The files will fit in a report with 2 columns %d high\n $RESULT
The files will fit in a report with 2 columns 11 high
$ printf %d $FILE_COUNT
22

Comando If and else


NUM_ORDERS=`ls -1 | wc -l`
if [ $NUM_ORDERS -lt $TOOFEW ] ; then
printf %s\n Too few orders...but will process them anyway
elif [ $NUM_ORDERS -gt $TOOMANY ] ; then
printf %s\n There are many orders. Processing may take a long time
else
printf %s\n Starting to process the orders
fi

O Comando Case
O comando case compara a varivel com diversos
valores, e caso corresponda um dos valores o comando
associado ser executado. O comando case facilita nos
casos onde existem muitas condies e tomada de deciso
diferenciada.
printf %s -> 1 = delete, 2 = archive. Please choose one
read REPLY
case $REPLY in
1) rm $TEMPFILE ;;
2) mv $TEMPFILE $TEMPFILE.old ;;
*) printf %s\n $REPLY was not one of the choices ;;
esac

Comando while loop


Em alguns momento precisamos que um comando
seja executado repetidas vezes. O Comando while repete
determinado(s) comando(s) enquanto o teste condicional
for verdadeiro.
printf %s\n Informe o nome do arquivo desejado ou control-d para sair
while read -p Arquivo ? ARQ; do
if test -f $ARQ ; then
printf %s\n Arquivo encontrado...
else
printf %s\n [ERRO]: Arquivo no encontrado
fi
done

Until Loop
printf "Informe o nome do arquivo ou o sera utilizado o arquivo padro.\n"
until test -f $ARQ ; do
printf %s\n Esperando...
sleep 30
done

O comando For
#!/bin/bash
# forloop.sh: Count from 1 to 9
for (( COUNTER=1; COUNTER<10; COUNTER++ )) ; do
printf The counter is now %d\n $COUNTER
done
exit 0

Parmetros de Entrada
$ cat test2
#!/bin/bash
# testing two command line parameters
total=$[ $1 * $2 ]
echo The first paramerer is $1.
echo The second parameter is $2.
echo The total value is $total.
$ ./test2 2 5
The first paramerer is 2.
The second parameter is 5.
The total value is 10.
$

Lendo o nome do programa


$ cat test5
#!/bin/bash
# testing the $0 parameter
echo The command entered is: $0
$ ./test5
The command entered is: ./test5
$ /home/rich/test5
The command entered is: /home/rich/test5
$

Parmetros Especiais
$ cat test8
#!/bin/bash
# getting the number of parameters
echo There were $# parameters supplied.
$ ./test8
There were 0 parameters supplied.
$ ./test8 1 2 3 4 5
There were 5 parameters supplied.
$ ./test8 1 2 3 4 5 6 7 8 9 10
There were 10 parameters supplied.

Trabalhando com opes


$ cat test15
#!/bin/bash
# extracting command line options as parameters
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found the -a option" ;;
-b) echo "Found the -b option";;
-c) echo "Found the -c option" ;;
*) echo "$1 is not an option";;
esac
shift
done
$ ./test15 -a -b -c -d
Found the -a option
Found the -b option
Found the -c option
-d is not an option

$ cat test17
#!/bin/bash
# extracting command line options and values
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found the -a option";;
-b) param="$2"
echo "Found the -b option, with parameter value $param"
shift 2;;
-c) echo "Found the -c option";;
--) shift
break;;
*) echo "$1 is not an option";;
esac
shift
done
count=1
for param in "$@"
do
echo "Parameter #$count: $param"
count=$[ $count + 1 ]
done

$ ./test17 -a -b test1 -d
Found the -a option
Found the -b option, with parameter value test1
-d is not an option
$

O Comando getopts
$ cat test19
#!/bin/bash
# simple demonstration of the getopts command
while getopts :ab:c opt
do
case "$opt" in
a) echo "Found the -a option" ;;
b) echo "Found the -b option, with value $OPTARG";;
c) echo "Found the -c option" ;;
*) echo "Unknown option: $opt";;
esac
done
$ ./test19 -ab test1 -c
Found the -a option
Found the -b option, with value test1
Found the -c option
$

A linux Solutions agradece sua participao neste


Treinamento Hands-On

Para dvida, crticas ou sugestes envie um e-mail para


ouvidoria@linuxsolutions.com.br/
treinamento@linuxsolutions.com.br
Ou entre em contato atravs do telefone (21) 2526-7262

Das könnte Ihnen auch gefallen