Notas de Aula - MAC 211 - Laboratório de Programação
Aula anterior (aula 10)
Aula 11 - 6/4/2010
Continuação de Interpretador de Comandos (Shell)
- chmod 755 scriptname (dá permissão
de execucao e leitura a todos)
ou
- chmod +x scriptname
- chmod u+x scriptname (dá permissão
só para o dono do arquivo)
- O script pode ser executado com o comando ./scriptname
A primeira linha do script pode conter o nome do
interpretador do script, por
exemplo
Variáveis do ambiente (environment variables),
comando env
- PATH
- CDPATH
- PWD
- SHELL
- EDITOR
- HOSTNAME
- Para atribuir um valor: export VARNAME=VALUE
- Para ver o valor: echo $VARNAME
Comandos através de combinações de teclas:
- Ctrl-C cancela a execução
do programa corrente
- Ctrl-D gera código de final
de arquivo, tambem fim de
sessao de login
- flechas verticais: percorre história de comandos
- flechas horizontais: posicionamento na linha corrente
- TAB: completa atá onde dá
sem ambiguidade
- TAB TAB: mostra lista das
opções para completar (se houver
várias)
Caracteres especiais:
- " para juntar strings com espaço no meio
\ escape
Operadores
- ; para executar varios comandos na mesma linha
- & para executar programas em background
(retorna controle ao
shell
ao inves de esperar pelo término do programa)
Programação de scripts:
- if [ -e meu_arquivo -a -d meu_diretorio ] ; then
mv meu_arquivo meu_diretorio
else
echo "arquivo ou diretório
não existe"
fi-
for a in txt doc c cpp java ; do
rm meu_arquivo.$a
done-
while [ -d meu_dir ] ; do
date >> arquivo_log
ls -la meu_dir >> arquivo_log
echo -- SEPARADOR --
>> arquivo_log
sleep 60
done- $1, $2, é o primeiro e o segundo
parâmetros e assim por diante
- $# é o número de parâmetros
- Pode-se definir funções e muitas outras coisas.
Exemplos extraídos do Bash
Programming HOWTO:
- A simple backup script
#!/bin/bash
SRCD="/home/"
TGTD="/var/backups/"
OF=home-$(date +%Y%m%d).tgz
tar -cZf $TGTD$OF $SRCD
- A not-so-simple file renamer
#!/bin/sh
# renna: rename multiple files according to several rules
# written by felix hudson Jan - 2000
#first check for the various 'modes' that this program has
#if the first ($1) condition matches then we execute that portion of the
#program and then exit
# check for the prefix condition
if [ $1 = p ]; then
#we now get rid of the mode ($1) variable and prefix ($2)
prefix=$2 ; shift ; shift
# a quick check to see if any files were given
# if none then its better not to do anything than rename some
non-existent
# files!!
if [$1 = ]; then
echo "no files given"
exit 0
fi
# this for loop iterates through all of the files that we gave the
program
# it does one rename per file given
for file in $*
do
mv ${file} $prefix$file
done
#we now exit the program
exit 0
fi
# check for a suffix rename
# the rest of this part is virtually identical to the previous section
# please see those notes
if [ $1 = s ]; then
suffix=$2 ; shift ; shift
if [$1 = ]; then
echo "no files given"
exit 0
fi
for file in $*
do
mv ${file} $file$suffix
done
exit 0
fi
# check for the replacement rename
if [ $1 = r ]; then
shift
# i included this bit as to not damage any files if the user does not
specify
# anything to be done
# just a safety measure
if [ $# -lt 3 ] ; then
echo "usage: renna r [expression] [replacement] files... "
exit 0
fi
# remove other information
OLD=$1 ; NEW=$2 ; shift ; shift
# this for loop iterates through all of the files that we give the
program
# it does one rename per file given using the program 'sed'
# this is a sinple command line program that parses standard input and
# replaces a set expression with a give string
# here we pass it the file name ( as standard input) and replace the
nessesary
# text
for file in $*
do
new=`echo ${file} | sed s/${OLD}/${NEW}/g` # s substitutes, g is for
global (not only the 1st)
mv ${file} $new
done
exit 0
fi
# if we have reached here then nothing proper was passed to the program
# so we tell the user how to use it
echo "usage;"
echo " renna p [prefix] files.."
echo " renna s [suffix] files.."
echo " renna r [expression] [replacement] files.."
exit 0
# done!
Outros programas bem úteis em ambientes UNIX:
- ps
- kill (versão -1, boazinha, versão -9, radical)
- top (mostra lista ordenada de processos, uso de CPU,
memória, etc.).
Exercício em sala de aula: criação de um script
Próxima aula (aula 12)
Página de MAC211
Página do Fabio
Página do DCC