Transcript
Page 1: Automatizando Shell Script

Automatizando com Shell Script: uma breve introdução prática à

poderosa linguagem de comandos do mundo *nix

Daniel [email protected]

Page 2: Automatizando Shell Script

O que vamos ver hoje?

● Introdução sobre Shell Script

● Um curso básico de Shell Script

● Praticando aprendizado

Page 3: Automatizando Shell Script

Introdução

Page 4: Automatizando Shell Script

O que é Shell?

● Shell = Concha

Fonte: http://twiki.softwarelivre.org/bin/view/TWikiBar/TWikiBarPapo001

Page 5: Automatizando Shell Script

Para que usamos o Shell?

● Executar programas do sistema$ cd documentos

$ cat conteudo.txt

$ ls

$ rm arquivo_antigo.pdf

● MSDOS melhorado (bem melhorado!)

Page 6: Automatizando Shell Script

Existem opções de Shell?

● Bourne Shell (sh)

● Korn Shell (ksh)

● Bourne Again Shell (bash)

● C Shell (csh)

● TENEX C Shell (tcsh)

● Z Shell (zsh)

Page 7: Automatizando Shell Script

Qual a diferença do Shell Script?

● + que comandos básicos, possui estruturas de linguagens de programação– variáveis, if, for, while, ...

● Diversos usos– CGIs– instaladores– rotinas backup– rotinas de administração

Page 8: Automatizando Shell Script

Curso básico

Page 9: Automatizando Shell Script

O mínimo exigido

● Conhecimento básico de comandos Linux– (date, echo, etc)

● 1 editor● Lógica

Page 10: Automatizando Shell Script

Executando comandos

● Alguns comando básicos$ clear

$ cd /home/$USER

$ ls

$ date

Page 11: Automatizando Shell Script

Primeiro exemplo

● Um script reunindo um conjunto de comandos$ vi primeiro.sh

#!/bin/bash# primeiro.sh - Script para execucao de alguns# comandos.## 06/05/2009 Daniel Bauermann

# Limpar tela e listar arquivosclearcd /home/$USERls# Informa data/horadate

Page 12: Automatizando Shell Script

Explicando (1)Escolhendo o Shell

#!/bin/bash

● Deve ser a primeira linha● Deve iniciar com #!● Deve ser informado caminho completo

Page 13: Automatizando Shell Script

Explicando (2)Comentários

# primeiro.sh - Script para execucao de alguns# comandos.## 06/05/2009 Daniel Bauermann

● Não é obrigatório● Mas ajuda MUITO

Page 14: Automatizando Shell Script

Executando

● Ajustar permissão de execução$ chmod u+x primeiro.sh

● Rodar script$ ./primeiro.sh

Page 15: Automatizando Shell Script

Condições (1)Comando if

● O famigerado if● Testa um comando (não uma condição!)● Sintaxe:

if COMANDO

then

comandoselse

comandosfi

Page 16: Automatizando Shell Script

Condições (1)Comando if

● O famigerado if● Testa um comando (não uma condição!)● Sintaxe:

if test EXPRESSÃO

then

comandoselse

comandosfi

Page 17: Automatizando Shell Script

Condições (1)Comando if

● O famigerado if● Testa um comando (não uma condição!)● Sintaxe:

if [ EXPRESSÃO ]

then

comandoselse

comandosfi

Page 18: Automatizando Shell Script

Condições (2)Comando if

● Expressões

Descrição-lt menor que ( LessThan )-gt maior que ( GreaterThan )-le menor igual ( LessEqual )-ge maior igual ( GreaterEqual )-eq igual ( Equal )-ne diferente ( NotEqual )= igual ( string )!= diferente ( string )

Page 19: Automatizando Shell Script

Condições (3)Comando if

● Arquivos e união de expressões

Descrição-d diretório

-f arquivo

-a e lógico ( And )-o ou lógico ( Or )

man test

Page 20: Automatizando Shell Script

Segundo exemplo

● Criando uma condição de avaliação$ vi segundo.sh

#!/bin/bash# segundo.sh � Saudacao conforme o horario.## 06/05/2009 Daniel Bauermann

if [ `date +%H` -lt 13 ]then

echo � Bom dia�

elif [ `date +%H` -lt 18 ]; thenecho � Boa tarde�

elseecho � Boa noite�

fi

Page 21: Automatizando Shell Script

Variáveis

● Sintaxe atribuição:VARIAVEL=valor

(sem espaços entre =)

● Sintaxe uso:$VARIAVEL

● Sem prototipação

Page 22: Automatizando Shell Script

Segundo exemplo com variável

$ vi segundo.sh

#!/bin/bash# segundo.sh � Saudacao conforme o horario.## 06/05/2009 Daniel Bauermann

HORA=`date +%H`if [ ${HORA} -lt 13 ]then

echo � Bom dia�

elif [ ${HORA} -lt 18 ]; thenecho � Boa tarde�

elseecho � Boa noite�

fi

Page 23: Automatizando Shell Script

Recebendo dados

● Comando read● Sintaxe:

read VARIÁVEL

Page 24: Automatizando Shell Script

Terceiro exemplo

● Interagindo e limpando a tela$ vi terceiro.sh

#!/bin/bash# terceiro.sh � Le e limpa (ou não) a tela.## 06/05/2009 Daniel Bauermann

# Imprime pergunta e le resposta do usuarioecho � Deseja limpar a tela? [sn]�read RESPOSTA

# Limpa tela se pressionado Sif [ � ${RESPOSTA}� = � S� -o � ${RESPOSTA}� = � s� ]then

clear

fi

Page 25: Automatizando Shell Script

Laços (1)Comando while

● Executa enquanto um comando seja válido● Sintaxe:

while COMANDO

do

comandosdone

Page 26: Automatizando Shell Script

Quarto exemplo

● Um contador$ vi quarto.sh

#!/bin/bash# quarto.sh � Um simples contador.## 06/05/2009 Daniel Bauermann

# Imprime valores de 1 a 10NUMERO=0while [ ${NUMERO} -lt 10 ]do

NUMERO=$((NUMERO+1))

echo � Contando: ${NUMERO}�

done

Page 27: Automatizando Shell Script

Laços (1)Comando for

● Executa individualmente valores de um conjunto

● Sintaxe:

for VARIÁVEL in LISTA

do

comandosdone

Page 28: Automatizando Shell Script

Quinto exemplo

● Contador com for

$ vi quinto.sh

#!/bin/bash# quinto.sh � Um simples contador com � for� .## 06/05/2009 Daniel Bauermann

# Imprime valores de uma listafor NUMERO in um dois três quatro cindodo

echo � Contando: ${NUMERO}�

done

Page 29: Automatizando Shell Script

O poder do pipe (|)

● Redireciona saída de um comando como para entrada de outro

● Exemplo:$ ls | wc -l

Page 30: Automatizando Shell Script

Praticando

Page 31: Automatizando Shell Script

Exercício 1

Listar todos os usuários

cadastrados no meu Linux

Page 32: Automatizando Shell Script

Exercício 1

Listar todos os usuários

cadastrados no meu Linux

● Listando conteúdo de arquivos: cat

Page 33: Automatizando Shell Script

Exercício 1

Listar todos os usuários

cadastrados no meu Linux

● Listando conteúdo de arquivos: cat

● Cortando em pedaços: cut

Page 34: Automatizando Shell Script

Exercício 1

Listar todos os usuários

cadastrados no meu Linux

● Listando conteúdo de arquivos: cat

● Cortando em pedaços: cut

● Substituindo strings: tr

Abuse do man

Page 35: Automatizando Shell Script

Solução exercício 1

$ vi exercicio1.sh

#!/bin/bash# exercicio1.sh � Lista usuarios do sistema.## 06/05/2009 Daniel Bauermann

# Le usuarios e formata saidacat /etc/passwd | cut -d : -f 1,5 | tr : '\t'

Page 36: Automatizando Shell Script

Exercício 2

Listar todos os usuários

cadastrados no meu Linux

(resolver com while )

● Dica: cat ARQUIVO | while read LINHA

Page 37: Automatizando Shell Script

Solução exercício 2

$ vi exercicio2.sh

#!/bin/bash# exercicio2.sh � Lista usuarios do sistema.## 06/05/2009 Daniel Bauermann

# Le usuarios e formata saidaecho -e � Usuário\tNome�cat /etc/passwd | while read LINHAdo

USUARIO=`echo ${LINHA} | cut -d : -f 1`

NOME=`echo ${LINHA} | cut -d : -f 5`

echo -e � ${USUARIO}\t${NOME}�

done

Page 38: Automatizando Shell Script

Exercício 3

E o meu backup? Não vou fazer?

● Definir arquivos a copiar (façamos de maneira elegante: crie uma variável)

● Definir destino da copia● Criar!

Page 39: Automatizando Shell Script

Solução exercício 3

$ vi meu_backup.sh

#!/bin/bash# meu_backup.sh � Criar copia de meus arquivos.## 06/05/2009 Daniel Bauermann

### VariaveisARQUIVO_TGZ=`date +� /tmp/copia_%Y%m%d-%H%M.tgz� `DIRETORIOS_COPIAR=� /etc /home�

### Execucaotar cvzf ${ARQUIVO_TGZ} ${DIRETORIOS_COPIAR}## (copia para o local apropriado...) ### Remove arquivo temporarioif [ -f ${ARQUIVO_TGZ} ]; then

rm ${ARQUIVO_TGZ}

fi

Page 40: Automatizando Shell Script

Sobrou tempo?

Page 41: Automatizando Shell Script

Melhorando a aparência

● Criar “janelas” com dialog● Versões para ambiente X:

– Xdialog– Kdialog– gdialog– Zenity

Page 42: Automatizando Shell Script

Veja com seus próprios olhos (1)

$ dialog --msgbox 'Meu nome é XYZ' \

5 40

$ dialog --title 'Preencha' \

--inputbox 'Informe seu nome' 0 0

$ dialog --title 'Calendário' \

--calendar '' 0 0

Page 43: Automatizando Shell Script

Veja com seus próprios olhos (2)

$ dialog --title 'Opções' \

--menu 'Escolha as suas' \

0 0 0 \

um 'Um' \

dois 'Dois' \

três 'Três'

Page 44: Automatizando Shell Script

Veja com seus próprios olhos (3)

$ dialog --title 'Opções' \

--checklist 'Escolha as suas' \

0 0 0 \

um 'Um' off \

dois 'Dois' off \

três 'Três' on

Abuse do man

Page 45: Automatizando Shell Script

Sexto exemplo● Um exemplo “gráfico”

$ vi sexto.sh

#!/bin/bash# sexto.sh � Usando o dialog.## 06/05/2009 Daniel Bauermann

# Solicita nome e armazena em variavaelNOME=$( dialog --title � Sexto� --stdout \

--inputbox � Informe seu nome:� 0 0 )

# Emite saudacaodialog --title � Sexto� --msgbox � Olá ${NOME}� 0 0

Page 46: Automatizando Shell Script

Finalizando

Page 47: Automatizando Shell Script

E agora, o que fazer?

● Pense em suas tarefas cotidianas● Encontre algo para automatizar● Elabore● Arregace as mangas● Tente, experimente● Diverta-se acima de tudo!!!

Page 48: Automatizando Shell Script

Referências

● Aurélio Marinho Jargas– http://aurelio.net/shell/

● Papo de Botequim – Júlio Neves– http://www.julioneves.com

Page 49: Automatizando Shell Script

Automatizando com Shell Script: uma breve introdução prática à

poderosa linguagem de comandos do mundo *nix

Perguntas?

Daniel [email protected]

Page 50: Automatizando Shell Script

Apresentações

● 06/05/2009 – [SoftwareLivreVS] Semana da Informática IENH - Novo Hamburgo - RS

Page 51: Automatizando Shell Script

Copyright (c) 2009, Daniel R. Bauermann

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of the Anauê Soluções em Informática nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FORA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER ORCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, ORPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OFLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDINGNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THISSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


Top Related