├── .gitignore ├── 01-Introducao e Conceitos Basicos ├── README.md ├── exemplos │ ├── hello.1.sh │ ├── hello.2.sh │ └── sysinfo.1.sh └── exercicios │ └── ex.01.md ├── 02-Variaveis ├── README.md ├── exemplos │ ├── agenda.1.sh │ ├── agenda.2.sh │ ├── args.1.sh │ └── sysinfo.2.sh └── exercicios │ ├── ex.01.md │ ├── ex.02.md │ ├── ex.03.md │ └── ex.04.md ├── 03-Aspas e Argumentos de linha de comando ├── README.md ├── exemplos │ ├── args.1.sh │ └── aspas.1.sh └── exercicios │ ├── ex.01.md │ ├── ex.02.md │ └── ex.03.md ├── 04-Datas e Substituição de Shell ├── README.md ├── exemplos │ ├── backup.1.sh │ ├── backup.2.sh │ └── sysinfo.3.sh └── exercicios │ ├── ex.01.md │ ├── ex.02.md │ └── ex.03.md ├── 05-Redirecionadores e Conectores ├── README.md ├── exemplos │ ├── busca.1.sh │ ├── busca.2.sh │ ├── files.1.sh │ ├── files.2.sh │ └── files.3.sh └── exercicios │ ├── ex.01.md │ ├── ex.02.md │ └── ex.03.md ├── 06-Aritmetica no Shell ├── README.md ├── exemplos │ ├── calculadora.1.sh │ ├── idade.1.sh │ ├── media.1.sh │ └── soma.1.sh └── exercicios │ ├── ex.01.md │ ├── ex.02.md │ └── ex.03.md ├── 07-Testes de Condições ├── README.md ├── exemplos │ ├── busca.3.sh │ ├── idade.2.sh │ └── media.2.sh └── exercicios │ ├── ex.01.md │ ├── ex.02.md │ └── ex.03.md ├── 08-Estruturas Condicionais ├── README.md ├── exemplos │ ├── busca.4.sh │ ├── busca.5.sh │ ├── calculadora.2.sh │ └── media.3.sh └── exercicios │ ├── ex.01.md │ ├── ex.02.md │ └── ex.03.md ├── 09-Estruturas de Repetição ├── README.md ├── exemplos │ ├── busca.6.sh │ ├── calculadora.3.sh │ ├── linhas.1.sh │ └── palavras.1.sh └── exercicios │ ├── ex.01.md │ ├── ex.02.md │ └── ex.03.md ├── 10-Funções e Modularização └── README.md ├── 11-Arrays e Strings └── README.md ├── 12-Mini Projeto 1 ├── README.md └── projeto.v1.sh ├── 13-AWK ├── README.md ├── exemplos │ ├── alunos.txt │ ├── cursos.awk │ ├── matriculas.sh │ └── nomes.awk └── exercicios │ ├── atividades.md │ ├── diasdetrabalho.md │ ├── nomes.md │ └── servicos.txt ├── 14-SED ├── README.md ├── exemplos │ ├── ips.txt │ ├── linha-em-branco.md │ ├── maquinas.txt │ ├── mascara.md │ └── update.md └── exercicios │ ├── manutencao.md │ ├── mascara.md │ └── redes.txt ├── 15-Interface gráfica ├── README.md ├── exemplos │ ├── filtrar-arq.sh │ └── form-curso.sh └── exercícios │ ├── arquivos.md │ ├── forms.md │ └── usuarios.md ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ignore/* 2 | *~ 3 | *swp 4 | -------------------------------------------------------------------------------- /01-Introducao e Conceitos Basicos/README.md: -------------------------------------------------------------------------------- 1 | # Introdução e Conceitos Básicos 2 | 3 | * Scripts são arquivos texto 4 | * Precisam de permissão de escrita e execução 5 | * Cabeçalho #!/bin/bash 6 | 7 | # Comandos Básicos 8 | 9 | * echo 10 | * read 11 | * date 12 | 13 | # Definição e acesso a variáveis 14 | 15 | * a=10 16 | * echo $a 17 | * echo ${a} 18 | 19 | # Videoaula(s) 20 | 21 | * Conceitos Básicos: https://youtu.be/5_6Vu3Z3X_w?si=JWFKdUoVFL0UusWw 22 | 23 | -------------------------------------------------------------------------------- /01-Introducao e Conceitos Basicos/exemplos/hello.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo "Hello, World!" 4 | -------------------------------------------------------------------------------- /01-Introducao e Conceitos Basicos/exemplos/hello.2.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo "Hello, World!" 4 | 5 | read -p "Qual o seu nome? " nome 6 | 7 | echo "Prazer em te conhecer, ${nome}!" 8 | -------------------------------------------------------------------------------- /01-Introducao e Conceitos Basicos/exemplos/sysinfo.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo -e "Olá! Este script exibe informações sobre o sistema!\n" 4 | 5 | echo -e "\nUso de memória:\n" 6 | free 7 | 8 | echo -e "\nUso de disco:\n" 9 | df 10 | 11 | echo -e "\nUsuários logados:\n" 12 | who 13 | 14 | echo -e "\nNúmero de arquivos e diretórios na pasta atual:\n" 15 | ls -1 | wc -l 16 | 17 | echo -e "\nNúmero de arquivos e diretórios na pasta home:\n" 18 | ls -1 ~ | wc -l 19 | -------------------------------------------------------------------------------- /01-Introducao e Conceitos Basicos/exercicios/ex.01.md: -------------------------------------------------------------------------------- 1 | # Exercício 01 2 | 3 | Estender o hello world #2 para, após dizer prazer em te conhecer, dizer qual a data de hoje e qual o dia da semana. 4 | 5 | -------------------------------------------------------------------------------- /02-Variaveis/README.md: -------------------------------------------------------------------------------- 1 | # Definição de variáveis 2 | 3 | * Variáveis definidas pelo usuário: 4 | * a=10 5 | * b="teste" 6 | * c=${b}${a} 7 | 8 | * Leitura de variáveis pela entrada padrão: 9 | * read teste 10 | * read - p "Escreva algo: " teste 11 | * echo $teste 12 | 13 | * Variáveis do Sistema: 14 | * echo ${PATH} 15 | * echo ${HOME} 16 | * echo ${SHELL} 17 | 18 | * Variáveis definidas pelo bash: 19 | * $1 $2 $3 $4 $5 $6 $7 ... 20 | * $* 21 | * $0 22 | 23 | # Videoaula(s) 24 | 25 | * Variáveis: https://www.youtube.com/watch?v=5_6Vu3Z3X_w&list=PLlfnoloSCPI2yAhYzUXE6V8-8DNC5nk0M&index=2&t=288s 26 | -------------------------------------------------------------------------------- /02-Variaveis/exemplos/agenda.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | nome="ifpb" 4 | fone="+55 (83) 3612 1200" 5 | mail="contato@ifpb.edu.br" 6 | 7 | echo "Esta entrada na minha agenda é:" 8 | echo -e "${nome}\t${fone}\t${mail}" 9 | -------------------------------------------------------------------------------- /02-Variaveis/exemplos/agenda.2.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | read -p "Digite seu nome: " nome 4 | read -p "Digite seu telefone: " fone 5 | read -p "Digite seu e-mail: " mail 6 | 7 | echo "Sua entrada na minha agenda é:" 8 | echo -e "${nome}\t${fone}\t${mail}" 9 | -------------------------------------------------------------------------------- /02-Variaveis/exemplos/args.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo "O nome do programa executado foi '$0'" 4 | 5 | echo "Todos argumentos de linha de comando passados para o programa foram '$*'" 6 | 7 | echo "Especialmente, os argumentos 1 e 2 foram: '${1}' e '${2}'" 8 | -------------------------------------------------------------------------------- /02-Variaveis/exemplos/sysinfo.2.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo -e "Olá! Este script exibe mais informações sobre o sistema!\n" 4 | 5 | echo -e "\nShell padrão:\n" 6 | echo ${SHELL} 7 | 8 | echo -e "\nCaminho padrão para programas:\n" 9 | echo ${PATH} 10 | 11 | echo -e "\nDiretório atual de trabalho:\n" 12 | echo ${PWD} 13 | 14 | echo -e "\nTempo de execução deste script:\n" 15 | echo ${SECONDS} 16 | -------------------------------------------------------------------------------- /02-Variaveis/exercicios/ex.01.md: -------------------------------------------------------------------------------- 1 | # Exercício 01 2 | 3 | O que é impresso na tela após a execução do seguinte script? 4 | 5 | ```bash 6 | #!/bin/bash 7 | 8 | a=10 9 | b=20 10 | c=$a$b 11 | d=$a$b$c 12 | echo ${d} 13 | ``` 14 | Explique a execução de cada linha do script. 15 | 16 | -------------------------------------------------------------------------------- /02-Variaveis/exercicios/ex.02.md: -------------------------------------------------------------------------------- 1 | # Exercício 02 2 | 3 | Escreva um script shell que leia 3 nomes e 3 telefones e imprima-os na tela. 4 | 5 | Melhore o script para que imprima primeiro os 3 telefones e depois os 3 nomes. 6 | 7 | -------------------------------------------------------------------------------- /02-Variaveis/exercicios/ex.03.md: -------------------------------------------------------------------------------- 1 | # Exercício 03 2 | 3 | Considere o script teste.sh descrito abaixo. 4 | 5 | ```bash 6 | #!/bin/bash 7 | echo $* 8 | echo $1 9 | echo $5 10 | echo $12 11 | echo $13 12 | ``` 13 | 14 | O que é impresso na tela após a execução do script teste.sh da seguinte forma: 15 | 16 | ```bash 17 | ./teste.sh a1 a2 a3 a4 "a5 a5" a6 a7 a8 'a9 a9' a10 a11 a12 a13 18 | ``` 19 | 20 | Como corrigir o script para que os argumentos de linha de comando 12 e 13 sejam exibidos corretamente? 21 | -------------------------------------------------------------------------------- /02-Variaveis/exercicios/ex.04.md: -------------------------------------------------------------------------------- 1 | # Exercício 04 2 | 3 | Considere o script teste.sh descrito abaixo. 4 | 5 | ```bash 6 | #!/bin/bash 7 | a="Brasil" 8 | aa="Brasileiro" 9 | aaa="Brasileirissimo" 10 | aaaa="Brasileirissimozinho" 11 | 12 | echo $a 13 | echo $aa 14 | echo $aaa 15 | echo $aaaa 16 | ``` 17 | 18 | O que é impresso na tela após a execução do script teste.sh? 19 | 20 | Como fazer para que, usando as variáveis 'a' e 'aa', o script imprima 'BrasilBrasileiro' (sem espaços) na tela? 21 | 22 | Como fazer para que, usando as variáveis 'a' e 'aa', o script imprima 'BrasilaBrasileiroa' (sem espaços) na tela? 23 | -------------------------------------------------------------------------------- /03-Aspas e Argumentos de linha de comando/README.md: -------------------------------------------------------------------------------- 1 | # Aspas e Argumentos de linha de comando 2 | 3 | 4 | * Caminho e Argumentos de linha de comando 5 | * Considere y.sh um script shell 6 | * Este pode ser executado de diversas formas: 7 | * ./y.sh 8 | * Neste caso, o caminho para o script é ./ 9 | * Nenhum argumento de linha de comando foi passado. 10 | * ./teste/y.sh 25 11 | * Neste caso, o caminho para o script é ./teste/ (O script está na pasta teste, que está no diretório atual) 12 | * Apenas um argumento de linha de comando foi passado: "25" 13 | * /home/usuario/y.sh a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 14 | * Neste caso, o caminho para o script é /home/usuario/ 15 | * Foram passados 10 argumentos de linha de comando: "a1" até "a10" 16 | 17 | 18 | * Aspas simples ('): 19 | * Todos os caracteres entre aspas simples são tratados de forma literal. 20 | * Útil para passar um programa como parâmetro para um comando: por exemplo sed e awk 21 | * sed 's/a/b/g' < entrada.txt 22 | * awk 'print $1 $2' < entrada.txt 23 | * Também é útil para imprimir caracteres especiais: 24 | * echo '$$' é um caractere especial, '\\' também 25 | 26 | 27 | * Aspas duplas ("): 28 | * Todos os caracteres entre aspas duplas são tratados de forma literal. 29 | * Exceto '$', '\\' e '`' 30 | * Útil para preservar espaços em branco, mas executando substituições de variáveis 31 | * echo "Segue o path: ${PATH}" 32 | * Também para preservar espaços quando atribuindo valores às variáveis 33 | * A="Meu nome é XUAUM" 34 | 35 | 36 | * Variáveis que representam os argumentos de linha de comando: 37 | * $1 $2 $3 $4 $5 $6 $7 ... (cada argumento individualmente) 38 | * $* (Todos os argumentos de linha de comando) 39 | * $0 (Comando executado) 40 | * $# (Número de argumentos passados pela linha de comando) 41 | * $$ (Número do processo em execução) 42 | * $! (Número do último comando executado) 43 | 44 | # Videoaula(s) 45 | 46 | * Aspas: https://www.youtube.com/watch?v=5_6Vu3Z3X_w&list=PLlfnoloSCPI2yAhYzUXE6V8-8DNC5nk0M&index=2&t=581s 47 | * Argumentos de linha de comando: https://www.youtube.com/watch?v=k8aS8CwmWKA&list=PLlfnoloSCPI2yAhYzUXE6V8-8DNC5nk0M&index=3&t=156s 48 | -------------------------------------------------------------------------------- /03-Aspas e Argumentos de linha de comando/exemplos/args.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo -e " * Este script foi executado usando o seguinte comando: ${0} ${*}" 4 | 5 | echo -e ' * Note que a variável "$0" representa apenas o comando:' $0 6 | 7 | echo -e ' * Enquanto a variável "$*" representa todos os argumentos de linha de comando:' $* 8 | 9 | echo -e ' * A variavel "$1" representa o primeiro argumento de linha de comando:' ${1} 10 | 11 | echo -e ' * A variavel "$2" representa o segundo argumento de linha de comando:' ${2} 12 | 13 | echo -e '\n ...\n' 14 | 15 | echo -e ' * Finalmente, a variavel "$#" representa o número de argumentos passados pela linha de comando:' ${#} 16 | -------------------------------------------------------------------------------- /03-Aspas e Argumentos de linha de comando/exemplos/aspas.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | A="10" 4 | B="22" 5 | 6 | echo -e ' * Foram criadas as variáveis $A e $B' 7 | echo -e " * Com os valores $A e $B" 8 | echo -e ' * Note que foi necessário utilizar aspas simples' 9 | echo -e ' * Caso contrário, seriam exibidos os valores das variáveis em vez de seus nomes:' 10 | echo -e " Foram criadas as variáveis $A e $B" 11 | echo -e ' * Acima, foi executado o seguinte comando: echo -e "Foram criadas as variáveis $A e $B"' 12 | -------------------------------------------------------------------------------- /03-Aspas e Argumentos de linha de comando/exercicios/ex.01.md: -------------------------------------------------------------------------------- 1 | # Exercício 01 2 | 3 | O que é impresso na tela após a execução do seguinte script? 4 | 5 | ```bash 6 | #!/bin/bash 7 | 8 | a=10 9 | b=20 10 | 11 | echo a 12 | echo "a" 13 | echo "$a" 14 | echo '$a' 15 | 16 | echo "o valor de $b é $b" 17 | echo 'o valor de $b é $b' 18 | echo "o valor de "'$b'" é $b" 19 | 20 | ``` 21 | 22 | -------------------------------------------------------------------------------- /03-Aspas e Argumentos de linha de comando/exercicios/ex.02.md: -------------------------------------------------------------------------------- 1 | # Exercício 02 2 | 3 | Escreva um script shell que receba 10 argumentos de linha de comando e imprima-os na tela na ordem reversa. 4 | 5 | Melhore o script para que imprima 2 argumentos por linha, separados por uma tabulação. 6 | 7 | Melhore o script para que imprima, antes de cada argumento, o nome da variável correspondente no shell (com $). 8 | -------------------------------------------------------------------------------- /03-Aspas e Argumentos de linha de comando/exercicios/ex.03.md: -------------------------------------------------------------------------------- 1 | # Exercício 03 2 | 3 | Considere o script teste.sh descrito abaixo. 4 | 5 | ```bash 6 | #!/bin/bash 7 | 8 | a="$*" 9 | b='$*' 10 | c="$#" 11 | 12 | echo '$a' 13 | echo '$b' 14 | echo '$c' 15 | 16 | echo "$a" 17 | echo "$b" 18 | echo "$c" 19 | 20 | ``` 21 | 22 | O que é impresso na tela após a execução do script teste.sh da seguinte forma: 23 | 24 | ```bash 25 | ./teste.sh arg1 arg2 arg3 arg4 26 | ``` 27 | -------------------------------------------------------------------------------- /04-Datas e Substituição de Shell/README.md: -------------------------------------------------------------------------------- 1 | # Datas e Substituição de Shell 2 | 3 | 4 | * Datas 5 | * calendar 6 | * cal 7 | * date 8 | * date [options...] [+format] 9 | * date 10 | * Saída: Ter Set 25 10:33:19 BRT 2018 11 | * date '+%d.%m.%y' 12 | * Saída: 25.09.18 13 | * date '+%a, %d.%m.%Y' 14 | * Saída: Ter, 25.09.2018 15 | * date "+%H:%M" 16 | * Saída: 19:07 17 | * date "+%s" 18 | * Saída: 1537882750 19 | * Significa o número de segundos desde 01-01-1970 00:00:00 UTC 20 | 21 | 22 | * Substituição de shell (também conhecido como substituição de comandos): 23 | * Sintaxe: 24 | * $(date) 25 | * `date` 26 | * O comando entre $() é executado e o seu resultado (o que o comando exibiria na tela) toma o seu lugar no script 27 | * Exemplos: 28 | * echo "A data de hoje é $(date +%d.%m.%y)" 29 | * Antes desta linha ser executada, o shell executa o comando date +%d.%m.%y, que imprimiria 26.09.18 na tela. 30 | * Em seguida, o shell substitui $(date +%d.%m.%y) por 26.09.18 na linha original 31 | * Esta se torna: echo "A data de hoje é 26.09.18" 32 | * E a saída do comando é: "A data de hoje é 26.09.18" 33 | * DIA="$(date +%d)" 34 | * MES="$(date +%m)" 35 | * ANO="$(date +%Y)" 36 | * echo "Estamos no dia ${DIA} de ${MES} do ano de ${ANO}." 37 | * ARQUIVOS="$(ls)" 38 | 39 | # Videoaula(s) 40 | 41 | * Comando date: https://www.youtube.com/watch?v=5_6Vu3Z3X_w&list=PLlfnoloSCPI2yAhYzUXE6V8-8DNC5nk0M&index=1&t=998s 42 | * Substituição de shell: https://www.youtube.com/watch?v=5_6Vu3Z3X_w&list=PLlfnoloSCPI2yAhYzUXE6V8-8DNC5nk0M&index=1&t=1122s 43 | -------------------------------------------------------------------------------- /04-Datas e Substituição de Shell/exemplos/backup.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo -e " *** Este script realiza um backup dos arquivos da pasta atual:" 4 | ls -1 5 | 6 | DATA="$(date +%d.%m.%y.%H.%M)" 7 | PASTA="/tmp/backup/$DATA" 8 | 9 | mkdir -p ${PASTA} 2> /dev/null 10 | 11 | cp * $PASTA 12 | 13 | echo -e " *** Feito!" 14 | -------------------------------------------------------------------------------- /04-Datas e Substituição de Shell/exemplos/backup.2.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo -e " *** Este script realiza um backup dos arquivos da pasta atual:" 4 | ls -1 5 | 6 | DATA="$(date +%d.%m.%y.%H.%M)" 7 | PASTA="/tmp/backup/$DATA" 8 | 9 | echo -e " *** Criando a pasta temporária ${PASTA}..." 10 | mkdir -p ${PASTA} 2> /dev/null 11 | 12 | echo -e " *** Copiando os arquivos (exceto .zip) para lá..." 13 | cp $(ls | grep -v *.zip) $PASTA 14 | 15 | echo -e " *** Compactando os arquivos" 16 | zip -r ./${DATA}.zip ${PASTA}/* 17 | 18 | echo -e " *** Excluindo a pasta temporária ${PASTA}..." 19 | rm -r ${PASTA} 2> /dev/null 20 | 21 | echo -e " *** Feito!" 22 | -------------------------------------------------------------------------------- /04-Datas e Substituição de Shell/exemplos/sysinfo.3.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo -e "---------------------------------------------------" >> logfile 4 | date >> logfile 5 | 6 | echo -e "Quem esta usando o sistema:" >> logfile 7 | who >> logfile 8 | 9 | echo -e "Informações sobre os discos:" >> logfile 10 | df >> logfile 11 | fdisk -l >> logfile 12 | 13 | echo -e "Informações sobre a memória:" >> logfile 14 | free >> logfile 15 | -------------------------------------------------------------------------------- /04-Datas e Substituição de Shell/exercicios/ex.01.md: -------------------------------------------------------------------------------- 1 | # Exercício 01 2 | 3 | O que é impresso na tela após a execução do seguinte script? 4 | 5 | ```bash 6 | #!/bin/bash 7 | 8 | a="$(pwd)" 9 | b="$(ls ${a})" 10 | 11 | echo $a 12 | echo $b 13 | ``` 14 | 15 | -------------------------------------------------------------------------------- /04-Datas e Substituição de Shell/exercicios/ex.02.md: -------------------------------------------------------------------------------- 1 | # Exercício 02 2 | 3 | Escreva um script shell que peça para o usuário digitar um dia, um mês e um ano e imprima o dia da semana correspondente. 4 | 5 | Melhore o script para que receba dia, mês e ano como argumentos de linha de comando. 6 | 7 | Melhore o script para que receba duas datas como argumentos de linha de comando: argumentos de 1 a 3 representam dia, mês e ano da data um, e os argumentos 4, 5 e 6 representam dia, mês e ano da data 2. 8 | -------------------------------------------------------------------------------- /04-Datas e Substituição de Shell/exercicios/ex.03.md: -------------------------------------------------------------------------------- 1 | # Exercício 03 2 | 3 | Considere o script teste.sh descrito abaixo. 4 | 5 | ```bash 6 | #!/bin/bash 7 | 8 | touch $1.$(date +%s) 9 | touch ${1}.zip 10 | 11 | timestamp=$(date +%s) 12 | touch $2.${timestamp} 13 | touch ${2}.${timestamp}.zip 14 | 15 | touch $3 16 | touch ${3}.zip 17 | 18 | touch ${timestamp} 19 | ls -la >> timestamp 20 | 21 | rm -rf $1 $2 $3 &> /dev/null 22 | 23 | ``` 24 | 25 | Explique a execução (linha por linha) do script teste.sh. Este foi executado da seguinte forma: 26 | 27 | ```bash 28 | ./teste.sh arg1 arg2 arg3 29 | ``` 30 | -------------------------------------------------------------------------------- /05-Redirecionadores e Conectores/README.md: -------------------------------------------------------------------------------- 1 | # Redirecionadores e Conectores 2 | 3 | 4 | * Redirecionadores 5 | * São usados para redirecionar as entradas/saídas de um comando para outro comando ou para um arquivo. 6 | * | 7 | * Conecta a saída do comando anterior com a entrada do comando seguinte. 8 | * Ex.: cat a.txt b.txt | grep nome 9 | * > >> 10 | * Redireciona a saída padrão do comando para um arquivo. 11 | * '>' sobrescreve o arquivo em questão. 12 | * '>>' adiciona a saída do comando ao final do arquivo, sem apagá-lo. 13 | * 2> 2>> 14 | * Redireciona a saída padrão de erros do comando para um arquivo. 15 | * '2>' sobrescreve o arquivo em questão. 16 | * '2>>' adiciona a saída do comando ao final do arquivo, sem apagá-lo. 17 | * &> &>> 18 | * Redireciona todas as saídas do comando para um arquivo. 19 | * '&>' sobrescreve o arquivo em questão. 20 | * '&>>' adiciona a saída do comando ao final do arquivo, sem apagá-lo. 21 | * < 22 | * Redireciona o arquivo para a entrada padrão do comando. 23 | * Ex.: ./teste.sh < arq.txt 24 | * << 25 | * Segue um documento. 26 | * Permite redirecionar a entrada padrão do comando para o documento escrito no bash. 27 | * Observe o exemplo file.3.sh para mais informações. 28 | * <<< 29 | * Segue uma string. 30 | * Permite redirionar a entrada padrão do comando para a string escrita no bash. 31 | * Equivalente a executar: echo "teste" | grep t 32 | * Seria executar: grep t <<<"teste" 33 | 34 | 35 | 36 | * Código de retorno 37 | * Todo comando executado no linux possui um código de retorno que informa se o comando foi bem sucedido ou não. 38 | * Este código pode ser acessado a através da variável $? 39 | * O Código 0 indica o sucesso da execução. 40 | * Códigos diferentes de 0 indicam falha. 41 | * Por exemplo: 42 | * o comando 'mkdir teste' retorna falha caso o diretório teste já exista. 43 | * E o comando 'grep txt teste' retorna falha caso não exista o padrão txt no arquivo teste. 44 | 45 | 46 | * Conectores 47 | * São usados para conectar um comando a outro. 48 | * | 49 | * O pipe também pode ser considerado um conector. 50 | * Ex.: cat a.txt b.txt | grep nome 51 | * ; 52 | * Usado para executar vários comandos na mesma linha. 53 | * Ex.: echo "Arquivo 1"; cat $1; echo "Arquivo 2"; cat $2 54 | * && 55 | * Usado como um condicional: O comando seguinte apenas é executado caso o primeiro obtenha sucesso. 56 | * I.e.: caso o primeiro comando tenha um código de retorno 0. 57 | * Ex.: mkdir teste && echo "Diretório criado com sucesso" 58 | * || 59 | * Usado como um condicional: O comando seguinte apenas é executado caso o primeiro falhe. 60 | * I.e.: caso o primeiro comando tenha um código de retorno diferente de 0. 61 | * Ex.: mkdir teste || echo 'Não foi possível criar o diretório "teste"' 62 | 63 | 64 | # Videoaula(s) 65 | 66 | 67 | * Redirecionadores: https://youtu.be/zdDGwOCPJNY?si=Qzq9_sxWLcqgLCJh 68 | * Conectores: (pipe) https://www.youtube.com/watch?v=zdDGwOCPJNY&t=1389s 69 | (and e or) https://youtu.be/z1pfp61JxtY?si=0VO3QK46aTSqw3GD 70 | 71 | -------------------------------------------------------------------------------- /05-Redirecionadores e Conectores/exemplos/busca.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | a1=$1; a2=$2; a3=$3; 4 | 5 | busca="127.0.0.1" 6 | 7 | cat ${a1} | grep $busca &> /dev/null && echo "${busca} encontrado no arquivo ${a1}" 8 | cat ${a2} | grep $busca &> /dev/null && echo "${busca} encontrado no arquivo ${a2}" 9 | cat ${a3} | grep $busca &> /dev/null && echo "${busca} encontrado no arquivo ${a3}" 10 | -------------------------------------------------------------------------------- /05-Redirecionadores e Conectores/exemplos/busca.2.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | a1=$1; a2=$2; a3=$3; 4 | 5 | busca="127.0.0.1" 6 | 7 | ls ${a1} &> /dev/null || echo "Sinto muito, arquivo ${a1} não existe. Saindo..." 8 | ls ${a1} &> /dev/null || exit 1 9 | 10 | cat ${a1} | grep $busca &> /dev/null && echo "${busca} encontrado no arquivo ${a1}" 11 | 12 | 13 | ls ${a2} &> /dev/null || echo "Sinto muito, arquivo ${a2} não existe. Saindo..." 14 | ls ${a2} &> /dev/null || exit 1 15 | 16 | cat ${a2} | grep $busca &> /dev/null && echo "${busca} encontrado no arquivo ${a2}" 17 | 18 | 19 | ls ${a3} &> /dev/null || echo "Sinto muito, arquivo ${a3} não existe. Saindo..." 20 | ls ${a3} &> /dev/null || exit 1 21 | 22 | cat ${a3} | grep $busca &> /dev/null && echo "${busca} encontrado no arquivo ${a3}" 23 | -------------------------------------------------------------------------------- /05-Redirecionadores e Conectores/exemplos/files.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo -e " *** Este script cria um conjunto de arquivos e diretorios:" 4 | 5 | a1=$1; a2=$2; a3=$3; 6 | 7 | echo -e " *** Tentando criar o diretório ${a1}" 8 | 9 | mkdir $a1 2> /dev/null 10 | echo "$a1" > "./${a1}/arquivo_${a1}" 11 | 12 | echo -e " *** Tentando criar o diretório ${a2}" 13 | 14 | mkdir $a2 2> /dev/null 15 | echo "$a2" > "./${a2}/arquivo_${a2}" 16 | 17 | echo -e " *** Tentando criar o diretório ${a3}" 18 | 19 | mkdir $a3 2> /dev/null 20 | echo "$a3" > "./${a3}/arquivo_${a3}" 21 | -------------------------------------------------------------------------------- /05-Redirecionadores e Conectores/exemplos/files.2.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo -e " *** Este script cria um conjunto de arquivos e diretorios:" 4 | 5 | a1=$1; a2=$2; a3=$3; 6 | 7 | echo "diretórios criados em $(date):" >> lista_de_diretorios 8 | echo ${a1} >> lista_de_diretorios 9 | echo ${a2} >> lista_de_diretorios 10 | echo ${a3} >> lista_de_diretorios 11 | 12 | echo -e " *** Tentando criar o diretório ${a1}" 13 | 14 | mkdir $a1 2> /dev/null 15 | echo "$a1" > "./${a1}/arquivo_${a1}" 16 | 17 | echo -e " *** Tentando criar o diretório ${a2}" 18 | 19 | mkdir $a2 2> /dev/null 20 | echo "$a2" > "./${a2}/arquivo_${a2}" 21 | 22 | echo -e " *** Tentando criar o diretório ${a3}" 23 | 24 | mkdir $a3 2> /dev/null 25 | echo "$a3" > "./${a3}/arquivo_${a3}" 26 | -------------------------------------------------------------------------------- /05-Redirecionadores e Conectores/exemplos/files.3.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | a1=$1; a2=$2; a3=$3; 4 | 5 | cat <> lista_de_diretorios 23 | echo ${a1} >> lista_de_diretorios 24 | echo ${a2} >> lista_de_diretorios 25 | echo ${a3} >> lista_de_diretorios 26 | 27 | echo -e " *** Tentando criar o diretório ${a1}" 28 | 29 | mkdir $a1 2> /dev/null && echo "OK!" 30 | echo "$a1" > "./${a1}/arquivo_${a1}" 31 | 32 | echo -e " *** Tentando criar o diretório ${a2}" 33 | 34 | mkdir $a2 2> /dev/null && echo "OK!" 35 | echo "$a2" > "./${a2}/arquivo_${a2}" 36 | 37 | echo -e " *** Tentando criar o diretório ${a3}" 38 | 39 | mkdir $a3 2> /dev/null && echo "OK!" 40 | echo "$a3" > "./${a3}/arquivo_${a3}" 41 | -------------------------------------------------------------------------------- /05-Redirecionadores e Conectores/exercicios/ex.01.md: -------------------------------------------------------------------------------- 1 | # Exercício 01 2 | 3 | O que é impresso na tela após a execução do seguinte script? 4 | 5 | ```bash 6 | #!/bin/bash 7 | 8 | a="$(pwd)" 9 | 10 | echo $a > teste 11 | echo $a >> teste 12 | 13 | cat teste 14 | ``` 15 | 16 | -------------------------------------------------------------------------------- /05-Redirecionadores e Conectores/exercicios/ex.02.md: -------------------------------------------------------------------------------- 1 | # Exercício 02 2 | 3 | O que é impresso na tela após a execução do seguinte script? 4 | 5 | ```bash 6 | #!/bin/bash 7 | 8 | cat $1 | grep $2 &> /dev/null && echo "OK" 9 | cat $1 | grep $2 &> /dev/null || echo "Not OK" 10 | 11 | exit 0 12 | ``` 13 | 14 | -------------------------------------------------------------------------------- /05-Redirecionadores e Conectores/exercicios/ex.03.md: -------------------------------------------------------------------------------- 1 | # Exercício 03 2 | 3 | Escreva um script shell que peça para o usuário digitar o nome de três diretórios do sistema. Crie o arquivo lista.txt contendo todos os arquivos de cada diretório passado. 4 | 5 | Melhore o script para que verifique se o diretório passado existe, exibindo uma mensagem de erro caso contrário. 6 | 7 | Melhore o script para que sejam criados dois arquivos, um com a lista.txt e outro com a lista de diretórios passados que não existem. 8 | -------------------------------------------------------------------------------- /06-Aritmetica no Shell/README.md: -------------------------------------------------------------------------------- 1 | # Aritmética no Shell 2 | 3 | * Existem algumas (várias) formas de realizar operações aritméticas no shell script. 4 | Neste curso, vamos focar duas delas: $(()) e bc. 5 | 6 | * $(( )) 7 | * Também conhecido como substituição aritmética (ou shell arithmetics), permite diversas operações com números inteiros: 8 | * a=$(( 12 * 10 )) 9 | * b=$(( 10 + $a )) 10 | * c=$(( $a + $b - 1 )) 11 | * echo $(( 2**4 )) 12 | * echo $(( 2**4 % 3 )) 13 | * echo $(( $a + $b * 2 )) 14 | * echo $(( a + b * 2 )) 15 | * echo $(( (a + b) * 2 )) 16 | 17 | * bc 18 | * Por sua vez, o comando bc permite a realização de aritmética de ponto flutuante. É necessária a instalação do pacote bc. 19 | * echo "7 / 3" | bc 20 | * Observe que é necessário informar o número de casas após a vírgula. 21 | * echo "scale=2; 7 / 3" | bc 22 | * Também é possível fazer transforação de base. 23 | 24 | * echo "obase=16; 10" | bc 25 | * echo "obase=8; 10" | bc 26 | * echo "obase=2; 10" | bc 27 | 28 | * Usando o 'here a string': 29 | 30 | * bc <<< "scale=2; 7 / 3" 31 | 32 | * Como o bc é um comando, variáveis devem sempre utilizar o $. A atribuição do resultado deve utilizar substituição de shell. 33 | 34 | * x=$( bc <<< "scale=2; $a / $b" ) 35 | 36 | * Seguem outras formas de realizar operações aritméticas no shell script: 37 | 38 | * expr 39 | * expr 12 + 10 40 | * let 41 | * let 'a=12*10' 42 | * echo $a 43 | * python 44 | * python -c 'print( 12 * 10 )' 45 | * $[] 46 | * a=$[ 12 * 10 ] 47 | * awk 48 | * awk " BEGIN { print 12 * 10 }" 49 | * declare 50 | * declare -i n; n=6/3; echo $n 51 | 52 | # Videoaula(s) 53 | 54 | * Aritmética no Bash: https://youtu.be/Y5HlZN2-yac?si=2h8RDYZDyCscrFsF 55 | -------------------------------------------------------------------------------- /06-Aritmetica no Shell/exemplos/calculadora.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Este script efetua uma operação aritmetica simples com dois operandos. 4 | 5 | read -p "digite o número x: " x 6 | read -p "digite uma operação (+, -, *, /, **, %): " op 7 | read -p "digite o número y: " y 8 | 9 | res="$(( $x $op $y ))" 10 | echo "o resultado da operação $x $op $y é ${res}" 11 | -------------------------------------------------------------------------------- /06-Aritmetica no Shell/exemplos/idade.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Este script calcula a média final do seu semestre do curso. 4 | 5 | read -p "digite a sua idade: " idade 6 | 7 | bb=$( bc <<<"obase=2; ${idade}" ) 8 | echo "A sua idade binária é ${bb}" 9 | -------------------------------------------------------------------------------- /06-Aritmetica no Shell/exemplos/media.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Este script calcula a média final do seu semestre do curso. 4 | 5 | read -p "digite a primeira nota: " n1 6 | read -p "digite a primeira nota: " n2 7 | read -p "digite a primeira nota: " n3 8 | 9 | med=$( echo "scale=2; (${n1} + ${n2} + ${n3})/3" | bc ) 10 | echo "A sua média neste semestre foi ${med}" 11 | -------------------------------------------------------------------------------- /06-Aritmetica no Shell/exemplos/soma.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Este script recebe 3 argumentos de linha de comando, e imprime a soma destes 4 | 5 | a1=$1 6 | a2=$2 7 | a3=$3 8 | 9 | echo 'A soma de $a1 com $a2 é:' $(( a1 + a2 )) 10 | echo 'A soma de $a1 com $a3 é:' $(( $a1 + $a3 )) 11 | echo 'A soma de $a2 com $a3 é:' $(( ${a2} + ${a3} )) 12 | 13 | echo 'A soma de $a1 com $a2 e $a3 é:' $(( a1 + $a2 + ${a3} )) 14 | -------------------------------------------------------------------------------- /06-Aritmetica no Shell/exercicios/ex.01.md: -------------------------------------------------------------------------------- 1 | # Exercício 01 2 | 3 | O que é impresso na tela após a execução do seguinte script? Explique cada linha do script. 4 | 5 | ```bash 6 | #!/bin/bash 7 | 8 | a=2 9 | b=4 10 | c=$(( a + b )) 11 | 12 | 13 | echo $(( a + b + c )) 14 | echo $(( a + b * c )) 15 | echo $(( (a + b) * c )) 16 | echo $(( a ** b )) 17 | echo $(( (a ** b) / c )) 18 | echo $(( (a ** b) % c )) 19 | 20 | ``` 21 | 22 | -------------------------------------------------------------------------------- /06-Aritmetica no Shell/exercicios/ex.02.md: -------------------------------------------------------------------------------- 1 | # Exercício 02 2 | 3 | O que é impresso na tela após a execução do seguinte script? Explique cada linha do script. 4 | 5 | ```bash 6 | #!/bin/bash 7 | 8 | x=10 9 | 10 | echo "10 / 3" | bc 11 | echo "${x} / 3" | bc 12 | echo "scale=2; 10 / 3" | bc 13 | echo "scale=2; ${x} / 3" | bc 14 | echo "obase=16; scale=0; 10 * 2" | bc 15 | bc <<<"obase=16; scale=0; 10 * 2" 16 | 17 | exit 0 18 | ``` 19 | 20 | -------------------------------------------------------------------------------- /06-Aritmetica no Shell/exercicios/ex.03.md: -------------------------------------------------------------------------------- 1 | # Exercício 03 2 | 3 | Escreva um script shell que peça para o usuário digitar um número e imprima-o em hexadecimal. 4 | 5 | Escreva um script shell que peça para o usuário digitar o nome de dois arquivos, e imprima a diferença entre o número de linhas destes. 6 | 7 | Escreva um script shell que peça para o usuário digitar a média obtida no semestre (abaixo de 70 e acima de 40) e imprima qual a nota este usuário precisa tirar na final para passar. 8 | 9 | Escreva um script shell receba como argumento de linha de comando 3 números, e imprima a porcentagem que cada um destes representa da soma dos 3. 10 | -------------------------------------------------------------------------------- /07-Testes de Condições/README.md: -------------------------------------------------------------------------------- 1 | # Testes de Condições 2 | 3 | * Uma das funções mais fundamentais de qualquer linguagem de programação é a possibilidade de executar (ou não) certos trechos de código dependendo de certas condições. 4 | 5 | * No bash, o teste de condições é feito com base na variável $?, que representa o código de retorno do último comando executado. Caso seu valor seja 0, o último comando obteve sucesso. 6 | 7 | * Desta forma, o teste pode ser verificado, por exemplo, usando os conectores || e &&: 8 | * (( 10 > 11 )) || exit 0 9 | * test -d /home/user && echo 'usuario existe' 10 | * [ ${a} -gt ${b} -a ${b} -gt ${c} ] && echo OK 11 | 12 | 13 | ### Teste de condições aritméticas com (( )): 14 | 15 | * Tal qual a substituição aritmética, permite o teste de condições com números inteiros: 16 | * (( 10 > 11 )) 17 | * (( 2*4 <= 12 )) 18 | * (( 3**2 == 3*3 )) 19 | * (( 27 % 2 == 12 - 10 )) 20 | * (( "${#}" == 4 )) 21 | * (( "${a}" > "${b}" )) 22 | 23 | * Exemplos utilizando conectores: 24 | * (( 25 % 2 == 0 )) && echo "par" 25 | * (( 31 % 2 == 0 )) || echo "impar" 26 | * (( "${a}" > "${b}" )) && (( "${b}" > "${c}" )) && echo 'a > b > c' 27 | 28 | 29 | ### Teste de condições com o comando test: 30 | 31 | * O comando test permite a verificação de condições relativas a números inteiros: 32 | * -gt significa maior que 33 | * test 12 -gt 10 34 | * -ge significa maior ou igual que 35 | * test 10 -ge 10 36 | * -lt significa menor que 37 | * test 11 -lt 10 38 | * -le significa menor ou igual que 39 | * test ${1} -le ${2} 40 | * -eq significa igual a 41 | * test 22 -eq 22 42 | * -ne significa não igual (ou diferente) 43 | * test 31 -ne 11 44 | 45 | * O comando test permite a verificação de condições relativas a strings: 46 | * == significa strings iguais 47 | * test a == a 48 | * != significa strings diferentes 49 | * test a != b 50 | * -z significa teste se a string é vazia 51 | * x="umdoistres"; test -z "$x" 52 | * -n significa teste se a string é não vazia 53 | * x="umdoistres"; test -n "$x" 54 | 55 | * O comando test permite a verificação de condições relativas a arquivos: 56 | * -d significa teste se o arquivo existe e é um diretório 57 | * test -d /home 58 | * -e significa teste se o arquivo existe 59 | * test -e ./bashrc 60 | * -f significa teste se o arquivo existe e é um arquivo comum 61 | * test -f /tmp/p.lock 62 | 63 | * O comando test pode ser utilizado de forma abreviada como [ EXPRESSÃO ]: 64 | * [ -d /home ] 65 | * [ 12 -gt 10 ] 66 | * [ "a" == "a" ] 67 | * [ "${x}" != "${y}" ] 68 | * [ -z "${x}" ] 69 | 70 | * Adicionalmente, várias condições podem ser conectadas por -a ( um AND, equivalente ao && ): 71 | * [ -n "${x}" -a ${x} -gt 0 ] && echo "Existe e é maior que zero" 72 | * [ -n "${x}" ] && [ ${x} -gt 0 ] && echo "Existe e é maior que zero" 73 | 74 | * Adicionalmente, várias condições podem ser conectadas por -o ( um OR, equivalente ao || ): 75 | * [ "${a}" -gt "${b}" -o "${a}" -gt "${c}" ] && echo '$a maior que $b ou $a maior que $c' 76 | * [ "${a}" -gt "${b}" ] || [ "${a}" -gt "${c}" ] && echo '$a maior que $b ou $a maior que $c' 77 | 78 | * Adicionalmente, a condição pode ser negada usando uma exclamação '!': 79 | * [ ! -d /home ] 80 | * [ ! -z "${x}" ] 81 | 82 | 83 | ### Teste de condições aritméticas para números reais (usando bc): 84 | 85 | * Por padrão, o bash não disponibiliza testes de condições para números reais. 86 | 87 | * É necessário, então, utilizar comandos externos (bc ou awk, por exemplo) através da substituição de shell. 88 | 89 | * Caso um teste dê verdadeiro, o bc imprime "1" na tela, caso dê falso imprime "0": 90 | * bc <<<"3.1 > 3" 91 | * bc <<<"3.1 < 3" 92 | 93 | * Desta forma, usando substituição de shell, o retorno do comando bc deve ser testado usando test ou (( )): 94 | * x=$(bc <<<"3.1 > 3"); (( ${x} == 1 )) && echo OK 95 | * x=$(bc <<<"3.1 > 3"); (( ${x} == 0 )) && echo FALHOU 96 | * x=$(bc <<<"3.1 > 3"); test "${x}" -eq 0 && echo FALHOU 97 | * x=$(bc <<<"3.1 > 3"); [ ${x} -eq 1 ] && echo OK 98 | 99 | * Ou, de forma direta (sem usar a variável $x): 100 | * (( $(bc <<<"3.1 > 3") == 1 )) && echo OK 101 | * [ $(bc <<<"3.1 > 3") -eq 1 ] || echo FALHOU 102 | 103 | 104 | # Videoaula(s) 105 | 106 | * Subistiuição aritmética: https://youtu.be/Y5HlZN2-yac 107 | * Comando test: https://youtu.be/pxt-PFzgHOw?list=PLlfnoloSCPI2yAhYzUXE6V8-8DNC5nk0M&t=792 108 | * Comando bc: https://www.youtube.com/watch?v=Y5HlZN2-yac&t=670s 109 | -------------------------------------------------------------------------------- /07-Testes de Condições/exemplos/busca.3.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | a1=$1; a2=$2; a3=$3; 4 | 5 | busca="127.0.0.1" 6 | 7 | [ ! -e ${a1} ] && echo "Sinto muito, arquivo ${a1} não existe. Saindo..." 8 | [ ! -e ${a1} ] && exit 1 9 | 10 | cat ${a1} | grep $busca &> /dev/null && echo "${busca} encontrado no arquivo ${a1}" 11 | 12 | 13 | test ! -e ${a2} && echo "Sinto muito, arquivo ${a2} não existe. Saindo..." 14 | test ! -e ${a2} && exit 1 15 | 16 | cat ${a2} | grep $busca &> /dev/null && echo "${busca} encontrado no arquivo ${a2}" 17 | 18 | 19 | ls ${a3} &> /dev/null || echo "Sinto muito, arquivo ${a3} não existe. Saindo..." 20 | ls ${a3} &> /dev/null || exit 1 21 | 22 | cat ${a3} | grep $busca &> /dev/null && echo "${busca} encontrado no arquivo ${a3}" 23 | -------------------------------------------------------------------------------- /07-Testes de Condições/exemplos/idade.2.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Este script verifica se você já pode dirigir. 4 | 5 | read -p "digite a sua idade: " idade 6 | 7 | (( "${idade}" >= 18 )) && echo "Você já pode dirigir! Que fantástico!" 8 | -------------------------------------------------------------------------------- /07-Testes de Condições/exemplos/media.2.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Este script calcula a média final do seu semestre do curso, e diz se você passou por média. 4 | 5 | read -p "digite a primeira nota: " n1 6 | read -p "digite a primeira nota: " n2 7 | read -p "digite a primeira nota: " n3 8 | 9 | med=$( echo "scale=2; (${n1} + ${n2} + ${n3})/3" | bc ) 10 | echo "A sua média neste semestre foi ${med}" 11 | 12 | [ $( bc <<< "${med} >= 7.0" ) -eq 1 ] && echo "Você Passou!" 13 | [ $( bc <<< "${med} >= 7.0" ) -eq 0 ] && echo "Você Reprovou!!" 14 | -------------------------------------------------------------------------------- /07-Testes de Condições/exercicios/ex.01.md: -------------------------------------------------------------------------------- 1 | # Exercício 01 2 | 3 | O que é impresso na tela após a execução do seguinte script? Explique cada linha do script. 4 | 5 | ```bash 6 | #!/bin/bash 7 | 8 | a=2 9 | b=4 10 | c=$(( a + b )) 11 | 12 | (( a + b + c > 10 )) && echo "OK" 13 | (( a % 2 == 0 )) && (( b % 2 == 0 )) && echo "OK" 14 | (( 2 ** 3 > 4 ** 2 )) && echo "OK" 15 | 16 | test -f ${a} && echo "OK" 17 | test ${a} -ge ${b} && echo "OK" 18 | test -z "${d}" && echo "OK" 19 | 20 | [ -d ${0} ] && echo "OK" 21 | [ -e ${0} ] && echo "OK" 22 | [ -f ${0} ] && echo "OK" 23 | ``` 24 | 25 | -------------------------------------------------------------------------------- /07-Testes de Condições/exercicios/ex.02.md: -------------------------------------------------------------------------------- 1 | # Exercício 02 2 | 3 | O que é impresso na tela após a execução do seguinte script? Explique cada linha do script. 4 | 5 | ```bash 6 | #!/bin/bash 7 | 8 | echo -e "Os preços podem ter casas decimais, Ex.: 10.25\n" 9 | 10 | read -p "Digite o preco do item 1: " p1 11 | read -p "Digite o preco do item 2: " p2 12 | read -p "Digite o preco do item 3: " p3 13 | read -p "Digite o preco do item 4: " p4 14 | 15 | total=$( bc <<< "scale=2; ${p1} + ${p2} + ${p3} + ${p4}" ) 16 | 17 | (( $( bc <<< "${total} >= 200.0" ) == "1" )) && total=$( echo "scale=2; ${total} * 0.85" | bc) 18 | 19 | echo "Você deve pagar $total Reais" 20 | 21 | ``` 22 | 23 | -------------------------------------------------------------------------------- /07-Testes de Condições/exercicios/ex.03.md: -------------------------------------------------------------------------------- 1 | # Exercício 03 2 | 3 | Escreva um script shell que peça para o usuário digitar um número e verifique se este é maior que 0 e menor que 10. 4 | 5 | Melhore o script anterior para que aceite que o usuário entre com números reais. Ex.: 22.5 ou 8.77. 6 | 7 | Escreva um script shell que peça para o usuário digitar a média obtida no semestre e verifique se o aluno passou, ficou na final ou foi reprovado. 8 | 9 | Escreva um script shell que receba como argumentos de linha de comando o preço do litro da gasolina e do álcool, e imprima se é melhor abastecer com gasolina ou com álcool. 10 | 11 | Melhore o script da questão anterior para que receba 4 argumentos: caso um argumento seja -a o argumento seguinte é o preço do álcool. Caso seja -g, o argumento seguinte é o preço da gasolina. 12 | 13 | Escreva um script que receba 4 nomes de arquivos como parâmetros de linha de comando e imprima na tela o nome do arquivo que possui mais linhas. 14 | 15 | Melhore o script anterior para que verifique se cada arquivo passado existe e não é um diretório. 16 | 17 | Melhore o script anterior para que exiba "ERRO 921" caso o argumento passado não exista e "ERRO 7818" caso o argumento passado seja um diretório. 18 | -------------------------------------------------------------------------------- /08-Estruturas Condicionais/README.md: -------------------------------------------------------------------------------- 1 | # Estruturas Condicionais 2 | 3 | * Aliadas aos testes de condições, as estruturas condicionais propiciam melhor legibilidade para os scripts, evitando o uso de conectores e permitindo vários comandos após a avaliação de uma condição. 4 | 5 | * No bash, temos as estruturas condicionais 'if - elif - else' e 'case - in'. 6 | 7 | 8 | ### if - then - fi: 9 | 10 | * A estrutura condicional mais básica: 11 | 12 | ```bash 13 | if (( $# < 3 )); then 14 | echo "Número de parâmetros insuficiente. Saindo..." 15 | exit 1 16 | fi 17 | 18 | if [ -e ${1} ]; then 19 | echo "Arquivo ${1} não encontrado." 20 | echo "Favor verificar se o argumento foi passado corretamente." 21 | exit 1 22 | fi 23 | ``` 24 | 25 | 26 | ### if - then - else - fi: 27 | 28 | * Testando se a condição é satisfeita ou não: 29 | 30 | ```bash 31 | if (( $# < 3 )); then 32 | echo "Número de parâmetros insuficiente. Saindo..." 33 | exit 1 34 | else 35 | arquivo_entrada="$1" 36 | arquivo_saida="$2" 37 | algoritmo_escolhido="$3" 38 | fi 39 | 40 | if [ -e ${1} ]; then 41 | echo "Arquivo ${1} não encontrado." 42 | echo "Favor verificar se o argumento foi passado corretamente." 43 | exit 1 44 | else 45 | num_linhas=$( cat ${1} | wc -l ) 46 | fi 47 | ``` 48 | 49 | ### if - then - elif - then - else - fi: 50 | 51 | * Testando várias condições ao mesmo tempo: 52 | 53 | ```bash 54 | if (( $# < 1 )); then 55 | echo "Número de parâmetros insuficiente. Saindo..." 56 | exit 1 57 | elif (( $# == 3 )); then 58 | arquivo_entrada="$1" 59 | arquivo_saida="$2" 60 | algoritmo_escolhido="$3" 61 | elif (( $# == 2 )); then 62 | arquivo_entrada="$1" 63 | arquivo_saida="$2" 64 | algoritmo_escolhido="basic" 65 | else 66 | arquivo_entrada="$1" 67 | arquivo_saida="/tmp/tmp.out" 68 | algoritmo_escolhido="basic" 69 | fi 70 | 71 | if [ -e ${1} ]; then 72 | echo "Arquivo '${1}' não encontrado." 73 | echo "Favor verificar se o argumento foi passado corretamente." 74 | exit 1 75 | elif [ -d ${1} ]]; then 76 | echo "Arquivo ${1} é um diretório." 77 | echo "Favor passar um arquivo regular como argumento." 78 | exit 1 79 | else 80 | num_linhas=$( cat ${1} | wc -l ) 81 | fi 82 | ``` 83 | 84 | ### case - in - esac: 85 | 86 | * Testando várias condições sobre uma mesma variável: 87 | 88 | ```bash 89 | read -p "digite uma tecla: " t 90 | 91 | case $t in 92 | 1) echo "Você Digitou a tecla 1" ;; 93 | 2) echo "Você Digitou a tecla 2" ;; 94 | 3) echo "Você Digitou a tecla 3" ;; 95 | q) echo "Saindo..." ;; 96 | *) echo "Não reconheço a tecla digitada..." ;; 97 | esac 98 | ``` 99 | 100 | * Usando o '|' como ou: 101 | 102 | ```bash 103 | read -p "digite uma tecla: " t 104 | 105 | case $t in 106 | 1) echo "Você Digitou a tecla 1" ;; 107 | 2) echo "Você Digitou a tecla 2" ;; 108 | 3) echo "Você Digitou a tecla 3" ;; 109 | q|Q) echo "Saindo..." ;; 110 | *) echo "Não reconheço a tecla digitada..." ;; 111 | esac 112 | ``` 113 | 114 | * Usando o '[' e ']' para agrupar condições: 115 | 116 | ```bash 117 | read -p "digite uma tecla: " t 118 | 119 | case $t in 120 | [123]) echo "Você Digitou a tecla $1" ;; 121 | q|Q) echo "Saindo..." ;; 122 | *) echo "Não reconheço a tecla digitada..." ;; 123 | esac 124 | ``` 125 | 126 | # Videoaula(s) 127 | 128 | * Comando IF: https://youtu.be/pxt-PFzgHOw?list=PLlfnoloSCPI2yAhYzUXE6V8-8DNC5nk0M 129 | -------------------------------------------------------------------------------- /08-Estruturas Condicionais/exemplos/busca.4.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | a1=$1; a2=$2; a3=$3; 4 | 5 | busca="127.0.0.1" 6 | 7 | if [ ! -e ${a1} ]; then 8 | echo "Sinto muito, arquivo ${a1} não existe. Saindo..." 9 | exit 1 10 | fi 11 | 12 | cat ${a1} | grep $busca &> /dev/null && echo "${busca} encontrado no arquivo ${a1}" 13 | 14 | 15 | if test ! -e ${a2}; then 16 | echo "Sinto muito, arquivo ${a2} não existe. Saindo..." 17 | exit 1 18 | fi 19 | 20 | cat ${a2} | grep $busca &> /dev/null && echo "${busca} encontrado no arquivo ${a2}" 21 | 22 | 23 | if ! ls ${a3} &> /dev/null; then 24 | echo "Sinto muito, arquivo ${a3} não existe. Saindo..." 25 | exit 1 26 | fi 27 | 28 | cat ${a3} | grep $busca &> /dev/null && echo "${busca} encontrado no arquivo ${a3}" 29 | -------------------------------------------------------------------------------- /08-Estruturas Condicionais/exemplos/busca.5.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | a1=$1; a2=$2; a3=$3; 4 | 5 | busca="127.0.0.1" 6 | 7 | # $a1 ------------------------------------------------------------------ 8 | if [ ! -e ${a1} ]; then 9 | echo "Sinto muito, arquivo ${a1} não existe. Saindo..." 10 | exit 1 11 | fi 12 | 13 | if cat ${a1} | grep $busca &> /dev/null; then 14 | echo "${busca} encontrado no arquivo ${a1}" 15 | fi 16 | 17 | # $a2 ------------------------------------------------------------------ 18 | if test ! -e ${a2}; then 19 | echo "Sinto muito, arquivo ${a2} não existe. Saindo..." 20 | exit 1 21 | fi 22 | 23 | if cat ${a2} | grep $busca &> /dev/null; then 24 | echo "${busca} encontrado no arquivo ${a2}" 25 | fi 26 | 27 | # $a3 ------------------------------------------------------------------ 28 | if ! ls ${a3} &> /dev/null; then 29 | echo "Sinto muito, arquivo ${a3} não existe. Saindo..." 30 | exit 1 31 | fi 32 | 33 | if cat ${a3} | grep $busca &> /dev/null; then 34 | echo "${busca} encontrado no arquivo ${a3}" 35 | fi 36 | -------------------------------------------------------------------------------- /08-Estruturas Condicionais/exemplos/calculadora.2.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Este script efetua uma operação aritmetica simples com dois operandos. 4 | 5 | read -p "digite o número x: " x 6 | 7 | echo "Escolha uma operação:" 8 | echo " Digite 1 para +" 9 | echo " Digite 2 para -" 10 | echo " Digite 3 para *" 11 | echo " Digite 4 para /" 12 | 13 | read c 14 | 15 | read -p "digite o número y: " y 16 | 17 | case ${c} in 18 | 1) op="+" ;; 19 | 2) op="-" ;; 20 | 3) op="*" ;; 21 | 4) op="/" ;; 22 | *) echo "Operação não reconhecida" 23 | echo "Na próxima vez, favor digitar 1, 2, 3, ou 4." 24 | exit 1 25 | ;; 26 | esac 27 | 28 | res="$(( $x $op $y ))" 29 | echo "o resultado da operação $x $op $y é ${res}" 30 | 31 | -------------------------------------------------------------------------------- /08-Estruturas Condicionais/exemplos/media.3.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Este script calcula a média final do seu semestre do curso, e diz se você passou por média. 4 | 5 | read -p "digite a primeira nota: " n1 6 | read -p "digite a segunda nota: " n2 7 | read -p "digite a terceira nota: " n3 8 | 9 | med=$( echo "scale=2; (${n1} + ${n2} + ${n3})/3" | bc ) 10 | echo "A sua média neste semestre foi ${med}" 11 | 12 | if [ $( bc <<< "${med} >= 7.0" ) -eq 1 ]; then 13 | echo "Você Passou!" 14 | else 15 | echo "Você Reprovou!!" 16 | fi 17 | -------------------------------------------------------------------------------- /08-Estruturas Condicionais/exercicios/ex.01.md: -------------------------------------------------------------------------------- 1 | # Exercício 01 2 | 3 | O que é impresso na tela após a execução do seguinte script? Explique cada linha do script. 4 | 5 | ```bash 6 | #!/bin/bash 7 | 8 | if (( "$#" != "1" )); then 9 | echo "*** Uso: ./${0} " 10 | exit 1 11 | fi 12 | 13 | infile=${1} 14 | 15 | if [ ! -f ${infile} ]; then 16 | echo "Arquivo ${infile} não existe. Saindo..." 17 | exit 1; 18 | fi 19 | 20 | nlines="$( cat ${infile} | wc -l)" 21 | 22 | if (( ${nlines} > 100 )); then 23 | echo "Arquivo Muito grande" 24 | elif (( ${nlines} < 10 )); then 25 | echo "Arquivo Muito pequeno" 26 | else 27 | cat ${infile} 28 | fi 29 | ``` 30 | 31 | -------------------------------------------------------------------------------- /08-Estruturas Condicionais/exercicios/ex.02.md: -------------------------------------------------------------------------------- 1 | # Exercício 02 2 | 3 | O que é impresso na tela após a execução do seguinte script? Explique cada linha do script. 4 | 5 | ```bash 6 | #!/bin/bash 7 | 8 | case "${1}" in 9 | start) /bin/daemon start ;; 10 | stop) /bin/daemon stop ;; 11 | status) /bin/daemon status anacron ;; 12 | 13 | restart) /bin/daemon stop 14 | /bin/daemon start ;; 15 | 16 | *) echo $"Usage: $0 {start|stop|restart|condrestart|status}" 17 | exit 1 ;; 18 | esac 19 | 20 | ``` 21 | 22 | -------------------------------------------------------------------------------- /08-Estruturas Condicionais/exercicios/ex.03.md: -------------------------------------------------------------------------------- 1 | # Exercício 03 2 | 3 | Escreva um script shell que peça para o usuário digitar 4 notas, elimine a menor, e calcule a média do aluno. 4 | 5 | Melhore o script anterior para que verifique se o usuário informou alguma nota vazia (apenas deu enter). Neste caso, deve sair do programa. 6 | 7 | Melhore o script anterior para que aceite 3 ou 4 notas como argumentos de linha de comando. Caso sejam passados 3, o programa deve apenas calcular a média. Caso sejam passados 4, o programa deve eliminar a menor nota e calcuar a média. 8 | 9 | Escreva um script shell que verifique se o usuário que o executou é root. Caso positivo, deve exibir uma mensagem de erro e sair. 10 | 11 | Escreva um script shell que receba um nome de arquivo como argumeto e exiba um menu com opções para: exibir as 10 primeiras linhas do arquivo, exibir as 10 últimas linhas do arquivo, ou exibir o úmero de lihas do arquivo. 12 | 13 | Melhore o script anterior para que verifique se o arquivo passado existe. 14 | -------------------------------------------------------------------------------- /09-Estruturas de Repetição/README.md: -------------------------------------------------------------------------------- 1 | # Estruturas de Repetição 2 | 3 | * Assim como todas as linguagens de programação modernas, o shell script também oferece estruturas capazes de repetir a execução de blocos de código até que determinada condição seja satisfeita. 4 | 5 | * No bash, temos as seguintes estruturas de repetição: 'for-do-done', 'for-in-do-done', 'while-do-done' e 'until-do-done'. 6 | 7 | 8 | ### for - do - done: 9 | 10 | * Estrutura utilizada quando se tem uma ideia muito boa sobre número de vezes que o bloco deve ser executado. 11 | 12 | 13 | ```bash 14 | for (( i=0; i<=10; i++ )) do 15 | echo -n "-" 16 | done 17 | echo "" 18 | 19 | for (( x=0; x<=5; x++ )) do 20 | echo "Linha ${x}" >> arquivo.txt 21 | done 22 | 23 | ``` 24 | 25 | * A parte 'i=0' é executada apenas uma vez, antes de qalquer execuçã dos comandos entre o do e o done. 26 | 27 | * A condição 'i<=5' é avaliada antes de cada execução d bloco entre o do e o done. Caso a condição seja falsa, a execução do laço for é finalizada. 28 | 29 | * A parte 'i++' é executada ao final de cada execução do bloco entre o do e o done. 30 | 31 | 32 | ### for - in - do - done: 33 | 34 | * Utilizado quando se conhece um grupo de valores bem definido e deseja-se que uma variável obtenha um valor desde grupo a cada iteração. 35 | 36 | ```bash 37 | for x in A B C D E; do 38 | touch ${x} 39 | echo ${x} >> ${x} 40 | done 41 | 42 | verbose="false" 43 | for arg in ${*}; do 44 | [ "${arg}" == "-v" ] && verbose="true" 45 | done 46 | 47 | for img in $(ls *.jpg); do 48 | echo "Copiando arquivo ${img} ..." 49 | cp ${img} /mnt/backup/pictures 50 | done 51 | ``` 52 | 53 | * Observe que o conjunto de valores que será atribuído à variável pode ser proveniente de uma substituição de variáveis (ex.: ${*}) ou de uma substituição de shell (ex.: $(ls) ). 54 | 55 | * Comandos comumente utilizados junto ao for-in-do-done: seq, cat, grep, head, ls, users... 56 | 57 | 58 | ### while-do-done: 59 | 60 | * Utilizado quando deseja-se que um conjunto de comandos seja executado enquanto determinada condição seja verdadeira: 61 | 62 | ```bash 63 | while [ "${word}" != "END" ]; do 64 | echo "será executado até que se digite END" 65 | read word 66 | done 67 | 68 | while (( "${SECONDS}" <= 10 )); do 69 | echo "Já se passaram ${SECONDS} segundos" 70 | sleep 1 71 | done 72 | ``` 73 | 74 | * O laço while-do-done també pode ser usado para iterar sobre cada linha de um arquivo de entrada. 75 | 76 | * Para tal, combina-se o while-do-done com o comando read e o redirecionador '<'. 77 | 78 | ```bash 79 | while rad linha; do 80 | echo ${linha} 81 | done < arquivo.txt 82 | ``` 83 | 84 | 85 | ### until - do - done: 86 | 87 | * Muito semelhando ao while-do-done, contudo o bloco de comandos é executado até que a condição seja satisfeita. 88 | 89 | 90 | ```bash 91 | echo "linha" > arquivo 92 | until (( $(cat arquivo | wc -l) == 10 )); do 93 | echo "linha" >> arquivo 94 | echo "O arquivo já possui $(cat arquivo | wc -l) linha(s)" 95 | done 96 | 97 | ``` 98 | 99 | # Videoaula(s) 100 | 101 | * Laço For: https://youtu.be/nWePERqMD4A?feature=shared 102 | * Laço while: https://youtu.be/26Xp-eiujqk?feature=shared 103 | 104 | -------------------------------------------------------------------------------- /09-Estruturas de Repetição/exemplos/busca.6.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | busca="127.0.0.1" 4 | 5 | echo "*** Iterando sobre todos os ${#} argumentos passados..." 6 | 7 | for a in ${*}; do 8 | 9 | if [ ! -e ${a} ]; then 10 | echo "Sinto muito, arquivo ${a} não existe. Saindo..." 11 | exit 1 12 | fi 13 | 14 | if cat ${a} | grep $busca &> /dev/null; then 15 | echo "${busca} encontrado no arquivo ${a}" 16 | else 17 | echo "${busca} não encontrado no arquivo ${a}" 18 | fi 19 | 20 | done 21 | -------------------------------------------------------------------------------- /09-Estruturas de Repetição/exemplos/calculadora.3.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Este script efetua uma operação aritmetica simples com dois operandos. 4 | 5 | continuar="s" 6 | while [ "${continuar}" == "s" ]; do 7 | 8 | read -p "digite o número x: " x 9 | 10 | echo "Escolha uma operação:" 11 | echo " Digite 1 para +" 12 | echo " Digite 2 para -" 13 | echo " Digite 3 para *" 14 | echo " Digite 4 para /" 15 | 16 | read c 17 | 18 | read -p "digite o número y: " y 19 | 20 | case ${c} in 21 | 1) op="+" ;; 22 | 2) op="-" ;; 23 | 3) op="*" ;; 24 | 4) op="/" ;; 25 | *) echo "Operação não reconhecida" 26 | echo "Na próxima vez, favor digitar 1, 2, 3, ou 4." 27 | exit 1 28 | ;; 29 | esac 30 | 31 | res="$(( $x $op $y ))" 32 | echo "o resultado da operação $x $op $y é ${res}" 33 | 34 | echo "..." 35 | read -p "Deseja realizar outra operação? (s/n)" continuar 36 | 37 | done 38 | 39 | echo "Bye Bye..." 40 | -------------------------------------------------------------------------------- /09-Estruturas de Repetição/exemplos/linhas.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | (( ${#} != 1 )) && echo " *** Uso: ${0} " 4 | (( ${#} != 1 )) && exit 1 5 | 6 | entrada=${1} 7 | cont_linha=0 8 | 9 | while read linha; do 10 | 11 | if (( cont_linha % 2 == 0 )); then 12 | echo ${linha} 13 | fi 14 | 15 | cont_linha=$(( cont_linha + 1 )) 16 | 17 | done < ${entrada} 18 | -------------------------------------------------------------------------------- /09-Estruturas de Repetição/exemplos/palavras.1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | (( ${#} != 1 )) && echo " *** Uso: ${0} " 4 | (( ${#} != 1 )) && exit 1 5 | 6 | entrada=${1} 7 | 8 | while read linha 9 | do 10 | echo "${linha}" | wc -w 11 | done < ${entrada} 12 | -------------------------------------------------------------------------------- /09-Estruturas de Repetição/exercicios/ex.01.md: -------------------------------------------------------------------------------- 1 | # Exercício 01 2 | 3 | O que é impresso na tela após a execução do seguinte script? Explique cada linha do script. 4 | 5 | ```bash 6 | #!/bin/bash 7 | 8 | echo "Foram passados ${#} arguentos:" 9 | 10 | for a in ${*}; do 11 | echo "${a}: $( echo ${a} | wc -c )" 12 | done 13 | ``` 14 | 15 | -------------------------------------------------------------------------------- /09-Estruturas de Repetição/exercicios/ex.02.md: -------------------------------------------------------------------------------- 1 | # Exercício 02 2 | 3 | O que é impresso na tela após a execução do seguinte script? Explique cada linha do script. 4 | 5 | ```bash 6 | #!/bin/bash 7 | 8 | read -p "Informe o nome de um arquivo: " arq 9 | 10 | if [ ! -f "${arq}" ]; then 11 | echo "Nome de arquivo inválido ou arquivo não existe." 12 | exit 1 13 | fi 14 | 15 | while read l; do 16 | if cat /etc/passwd | grep ${l} 2> /dev/null; then 17 | echo "Usuário ${l} existe no sistema" 18 | else 19 | echo "Usuário ${l} não existe no sistema" 20 | fi 21 | done < ${arq} 22 | 23 | ``` 24 | 25 | -------------------------------------------------------------------------------- /09-Estruturas de Repetição/exercicios/ex.03.md: -------------------------------------------------------------------------------- 1 | # Exercício 03 2 | 3 | Escreva um script shell que receba vários números como argumentos de linha de comando e imprima a média entre eles. 4 | 5 | Melhore o script anterior para que aceite números com casas decimais. 6 | 7 | Melhore o script anterior para que imprima também o maior e o menor número passado. 8 | 9 | Melhore o script anterior para que os números sejam passados, um por linha, pelo arquivo num.txt. 10 | 11 | Escreva um script shell que crie 100 arquivos na pasta /tmp. 12 | 13 | Melhore o script anterior para que o conteúdo de cada arquivo seja diferente. 14 | 15 | Escreva um script shell que receba um nome de arquivo como argumeto crie uma cópia deste arquivo, adicionando o número da linha no começo de cada linha. 16 | 17 | Melhore o script anterior para que verifique se o arquivo passado existe. 18 | -------------------------------------------------------------------------------- /10-Funções e Modularização/README.md: -------------------------------------------------------------------------------- 1 | # Funções e Modularização 2 | 3 | * O os scripts shell possibilitam a definição de funções. Desta forma, o código pode ficar mais organizado, legível e menos repetitivo, sendo menos propenso a falhas e mais fácil de ser mantido. 4 | 5 | * Uma vez definida, uma função se torna um comando interno para o shell atual. 6 | 7 | 8 | ```bash 9 | function ola() { 10 | echo 'oi' 11 | } 12 | 13 | function linha() { 14 | echo '----------------------------' 15 | } 16 | 17 | linha 18 | linha 19 | ola 20 | linha 21 | linha 22 | 23 | ``` 24 | 25 | * Assim como qualquer comando, uma função também aceita argumentos. 26 | 27 | * Dentro da função, as variáveis $1, $2, $3, ..., $* e $# assumem os valores referentes aos argumentos passados à função. 28 | 29 | 30 | ```bash 31 | function soma() { 32 | echo $(( ${1} + ${2} + ${3} + ${4} )) 33 | } 34 | 35 | ``` 36 | 37 | * Assim como os comandos, as funções também possuem um código de retorno, sendo que 0 representa sucesso e != 0 representa falha. 38 | 39 | * O código de retorno é capturado pela variável $?. 40 | 41 | 42 | ```bash 43 | function testa_arquivo() { 44 | [ -d "$1" ] && return 1; 45 | [ ! -e "$1" ] && return 2; 46 | return 0; 47 | } 48 | 49 | testa_arquivo /etc/passwd 50 | echo $? 51 | ``` 52 | 53 | * O texto que uma função imprime na tela pode ser capturado usando substituição de shell. 54 | 55 | 56 | ```bash 57 | function soma() { 58 | echo $(( ${1} + ${2} + ${3} + ${4} )) 59 | } 60 | 61 | y="$( soma 4 5 6 7 8 )" 62 | 63 | ``` 64 | 65 | * Observe que tanto as funções tem acesso às variáveis criadas em outros locais do script, quanto os outros locais do script tem acesso às variáveis criadas nas funções. 66 | 67 | * deste modo, podemos dizer que uma vez definida, uma variável é visível durante todo o ciclo de vida de um script. 68 | 69 | ```bash 70 | function echo_x() { 71 | echo ${x} 72 | } 73 | 74 | function def_y() { 75 | y=50 76 | } 77 | 78 | x=25 79 | echo_x 80 | def_y 81 | echo ${y} 82 | ``` 83 | 84 | ### Modularização: 85 | 86 | * Uma vez que temos várias funções definidas em um script, estas podem ser importadas para serem executadas por outros scripts usando o comando source. 87 | 88 | * Este comando executa cada linha do script importado no script atual, trazendo, assim, suas definições de funções, variáveis, exportações e outros. 89 | 90 | 91 | ```bash 92 | # File f.sh 93 | x=10 # Esta linha sera executada durante a importação 94 | echo "Esta linha tambem será executada $x." 95 | 96 | function xyz() { 97 | echo $x 98 | } 99 | ``` 100 | 101 | 102 | ```bash 103 | # File g.sh 104 | 105 | source f.sh # Importa o script f.sh (executa-o aqui, linha por linha) 106 | 107 | xyz 108 | 109 | ``` 110 | 111 | # Videoaula(s) 112 | 113 | * Funções: https://youtu.be/Z8xaBRijiTw?feature=shared 114 | * Modularização: https://youtu.be/Z8xaBRijiTw?list=PLlfnoloSCPI2yAhYzUXE6V8-8DNC5nk0M&t=405 115 | 116 | -------------------------------------------------------------------------------- /11-Arrays e Strings/README.md: -------------------------------------------------------------------------------- 1 | # Arrays e Strings 2 | 3 | * Um dos conceitos fundamentais de qualquer linguagem de programação é a utilização de arrays (ou vetores). 4 | 5 | * Um array (ou vetor) é uma variável que carrega várias variáveis, que podem ser acessadas usando um índice. 6 | 7 | * Existem várias formas de declarar um array em shell script. 8 | 9 | * O modo mais simples é usar um índice na hora de criar uma variável: 10 | 11 | ```bash 12 | A[3]=10 13 | ``` 14 | 15 | * Para usar um array, basta usar substituição de variáveis com o índice desejado: 16 | 17 | ```bash 18 | echo ${A[3]} 19 | ``` 20 | 21 | * Vamos criar um array maior para usar nos próximos exemplos: 22 | 23 | ```bash 24 | bike[7]=caloy 25 | bike[9]=moonark 26 | bike[0]=XiiMano 27 | bike[11]=barraCircular 28 | ``` 29 | 30 | * Como imprimir todos os valores que estão guardados no array: 31 | 32 | ```bash 33 | echo ${bike[*]} 34 | ``` 35 | 36 | * Outra forma (com tratamento especial para espaços): 37 | 38 | ```bash 39 | echo ${bike[@]} 40 | ``` 41 | 42 | * Como imprimir todas as chaves usadas como índices para o array: 43 | 44 | ```bash 45 | echo ${!bike[*]} 46 | ``` 47 | 48 | * Como imprimir o número ítens contidos no array: 49 | 50 | ```bash 51 | echo ${#bike[*]} 52 | ``` 53 | 54 | * Como imprimir o número ítens contidos no array: 55 | 56 | ```bash 57 | echo ${#bike[*]} 58 | ``` 59 | 60 | * Imprimindo o valor associado à chave 9: 61 | 62 | ```bash 63 | echo ${bike[9]} 64 | ``` 65 | 66 | * Uma segunda forma (muito útil) para criar arrays é usando parêntesis: 67 | 68 | ```bash 69 | bus=( setysa truns reunaidas Xorge ) 70 | echo ${bus[*]} 71 | echo ${!bus[*]} 72 | echo ${#bus[*]} 73 | ``` 74 | 75 | * Observe que como não atribuímos chaves aos valores, o sistems usa as chaves 0, 1, 2 e 3. 76 | 77 | * Para adicionar um novo item ao final de um array podemos usar o seguinte comando: 78 | 79 | ```bash 80 | bus[ ${ #bus[*] } ]=xicoBus 81 | ``` 82 | 83 | * Contudo, isto fica mais simples se usarmos a criação com parêntesis: 84 | 85 | ```bash 86 | bus=( ${bus[*]} ZeBus ) 87 | ``` 88 | 89 | * A mesma técnica pode ser usada para adicionar um item ao início do array: 90 | 91 | ```bash 92 | bus=( XuaoTur ${bus[*]} ) 93 | ``` 94 | 95 | * Ou para concatenar dois arrays: 96 | 97 | ```bash 98 | busbike=( ${bus[*]} ${bike[*]} ) 99 | ``` 100 | 101 | * Os arrays em shell também permitem o seu fatiamento. 102 | 103 | * O comando abaixo exibe os ítens do array busbike a partir da posição 3 (incluída): 104 | 105 | ```bash 106 | echo ${bus[*]:3} 107 | ``` 108 | 109 | * Enquanto o comando seguinte exibe 2 ítens do array busbike a partir da posição 3 (incluída): 110 | 111 | ```bash 112 | echo ${bus[*]:3:2} 113 | ``` 114 | 115 | * Por fim, os Arrays em shell permitem a utilização de strings como chaves (índices), os famosos arrays associativos. 116 | 117 | * Para usá-los, devemos declarar o array como associativo usando o comando declare: 118 | 119 | ```bash 120 | declare -A carros 121 | carros[Xelta]=10 122 | carros[XolkXixagen]=4 123 | carros[Xyunxay]=5 124 | ``` 125 | 126 | * Utilizamos os arrays associativos da mesma forma que os arrays normais: 127 | 128 | ```bash 129 | echo ${carros[*]} 130 | echo ${!carros[*]} 131 | echo ${#carros[*]} 132 | echo ${carros[Xelta]} 133 | ``` 134 | 135 | * Observe que as chaves (índices) não (necessariamente) ficam na mesma ordem de quando foram criados. 136 | 137 | * Para finalizar, é bem interessante saber que algumas operações que usamos sobre os arrays 138 | também podem ser usadas com strings: 139 | 140 | ```bash 141 | texto="Olha que coisa mais linda" 142 | echo ${texto} 143 | echo ${texto[*]} 144 | echo ${#texto} 145 | echo ${texto:1} 146 | echo ${texto:2} 147 | echo ${texto:3} 148 | echo ${texto:3:10} 149 | echo ${texto:3:11} 150 | echo ${texto:3:15} 151 | ``` 152 | 153 | # Videoaula(s): 154 | 155 | * Arrays e Strings: https://youtu.be/iV2AN-5vJrI?list=PLlfnoloSCPI2yAhYzUXE6V8-8DNC5nk0M 156 | 157 | -------------------------------------------------------------------------------- /12-Mini Projeto 1/README.md: -------------------------------------------------------------------------------- 1 | # Mini Projeto Número 1 2 | 3 | * O Mini Projeto utiliza um menu com diversas opções de navegação e manipulação de diretorios e arquivos utilizando um conjunto de comandos simples, funções e condicionais já aprendidas. 4 | -------------------------------------------------------------------------------- /12-Mini Projeto 1/projeto.v1.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | function diretorio () { 4 | echo "*** Os diretorios são: " 5 | for i in $(ls); do 6 | if [ -d $i ]; then 7 | echo " $i" 8 | fi 9 | done 10 | } 11 | 12 | function arquivo () { 13 | echo "*** Os arquivos são: " 14 | for j in $(ls); do 15 | if [ -f $j ]; then 16 | echo " $j" 17 | fi 18 | done 19 | } 20 | 21 | while true; do 22 | clear 23 | echo "*** SEJA BEM VINDO $(whoami) AO PROJETO ***" 24 | echo "*** VC ESTÁ NO $(pwd) ***" 25 | echo "___________________________________________" 26 | echo "*** Os arquivos são: " 27 | for i in $(ls); do 28 | if [ -f $i ]; then 29 | echo " $i" 30 | fi 31 | done 32 | echo "__________________________________________" 33 | echo "*** Os diretorios são: " 34 | for j in $(ls); do 35 | if [ -d $j ]; then 36 | echo " $j" 37 | fi 38 | done 39 | echo "__________________________________________" 40 | echo "Deseja fazer o que?" 41 | echo -n "a) ler um arquivo " 42 | echo "b) entrar em um diretorio" 43 | echo -n "c) ver uma preview do arquivo " 44 | echo "d) deletar um arquivo" 45 | echo -n "e) deletar um diretorio " 46 | echo "f) copiar um arquivo" 47 | echo -n "g) editar um arquivo " 48 | echo "h) voltar para o diretorio anterior" 49 | echo -n "i) mostrar diretório atual " 50 | echo "j) limpar a tela" 51 | echo "q) sair do menu" 52 | echo "" 53 | read -p "digite uma opção: " op 54 | if [ $op == "a" ]; then 55 | arquivo 56 | read -p "Digite qual arquivo: " arq 57 | if test -f $arq; then 58 | cat $arq 59 | else 60 | echo "vc não digitou um arquivo ou ele não existe" 61 | sleep 5 62 | fi 63 | fi 64 | 65 | if [ $op == "b" ]; then 66 | diretorio 67 | read -p "Digite um diretorio: " dir 68 | if test -d $dir; then 69 | cd $dir 70 | else 71 | echo "vc não digitou um diretorio ou ele não existe" 72 | sleep 5 73 | fi 74 | fi 75 | 76 | if [ $op == "c" ]; then 77 | arquivo 78 | read -p "Digite qual arquivo: " arq 79 | if test -f $arq; then 80 | head $arq 81 | else 82 | echo "vc não digitou um arquivo ou ele não existe" 83 | sleep 5 84 | fi 85 | fi 86 | 87 | if [ $op == "d" ]; then 88 | arquivo 89 | read -p "Digite qual arquivo: " arq 90 | if test -f $arq; then 91 | rm -r $arq 92 | else 93 | echo "vc não digitou um arquivo ou ele não existe" 94 | sleep 5 95 | fi 96 | fi 97 | 98 | if [ $op == "e" ]; then 99 | diretorio 100 | read -p "Digite qual diretorio: " dir 101 | if test -d $dir; then 102 | rmdir $dir 103 | else 104 | echo "vc não digitou um diretorio ou ele não existe" 105 | sleep 5 106 | fi 107 | fi 108 | 109 | if [ $op == "f" ]; then 110 | arquivo 111 | read -p "Digite qual arquivo: " arq 112 | if test -f $arq; then 113 | read -p "Digite como quer salvar: " sal 114 | cp $arq $sal 115 | else 116 | echo "vc não digitou um arquivo ou ele não existe" 117 | sleep 5 118 | fi 119 | fi 120 | 121 | if [ $op == "g" ]; then 122 | arquivo 123 | read -p "Digite qual arquivo: " arq 124 | if test -f $arq; then 125 | vim $arq 126 | else 127 | echo "vc não digitou um arquivo ou ele não existe" 128 | sleep 5 129 | fi 130 | fi 131 | 132 | if [ $op == "h" ]; then 133 | arquivo 134 | diretorio 135 | if [ $(pwd) != "/" ];then 136 | cd .. 137 | else 138 | echo "você está no topo" 139 | sleep 5 140 | fi 141 | 142 | fi 143 | 144 | if [ $op == "i" ]; then 145 | pwd 146 | sleep 5 147 | fi 148 | 149 | if [ $op == "j" ]; then 150 | clear 151 | fi 152 | 153 | if [ $op == "q" ]; then 154 | exit 1 155 | fi 156 | done 157 | -------------------------------------------------------------------------------- /13-AWK/README.md: -------------------------------------------------------------------------------- 1 | # AWK 2 | 3 | * Descrição 4 | * AWK é uma linguagem de programação que permite a manipulação de textos levando em consideração uma sequência de padrões. 5 | 6 | * Opções de comando 7 | * -f: Especifica o nome do arquivo que possui os comandos que serão executados. 8 | * -F: Define o que será o separador de campos (O espaço é o padrão). 9 | * -h: Informa as opções (Ajuda). 10 | * -v: Informa a versão. 11 | 12 | * Formato do comando 13 | * O comando awk é basicamente formado por: awk '/padrão/{ação}' "nomedoarquivo". 14 | * Onde o padrão é uma expressão regular, é necessário que ao menos uma ação ou um padrão seja digitado, caso contrário o comando awk não executará nada. 15 | 16 | 17 | 18 | * Regras do AWK 19 | * O AWK lê uma linha do arquivo por vez. 20 | * Para cada linha lida o AWK realiza as ações que foram informadas. 21 | * Caso não seja informado nenhum padrão o AWK não realizará nenhuma ação. 22 | * Caso não seja informada nenhuma ação o AWK realizará a sua ação padrão (print) 23 | * É possível realizar mais de uma ação separando cada uma delas por ponto e vírgula ";". 24 | 25 | 26 | * Variáveis internas 27 | * O AWK, assim como o bash, possui suas variáveis internas, são elas: 28 | * ARGC: Número de argumentos da linha de comando; 29 | * ARGV: Vetor com os argumentos da linha de comandos; 30 | * ENVIRON: Vetor com as variáveis de ambiente; 31 | * ERRNO: Armazena mensagem de erro; 32 | * FILENAME: Nome do arquivo de entrada que está sendo processado; 33 | * FNR: Número de linhas já processadas em um determinado arquivo; 34 | * FS: Separador de campos (Espaço vazio é o padrão); 35 | * NF: Números de campos presentes na linha que está sendo processada (último campo); 36 | * NR: Números de linhas já processadas. 37 | * $0: A linha que está sendo processada atualmente 38 | * $1,$2,$3,$...: Campos da linha que está sendo processada. 39 | 40 | ### Exemplo: 41 | * Suponhamos que há um arquivo de texto chamado "entrada.txt" e nesse arquivo temos o seguinte conteúdo: 42 | 43 | Nome Pontos 44 | José 103 45 | Andréia 50 46 | Henrique 22 47 | Júlia 150 48 | 49 | * Caso seja solicitado que apareça na tela apenas o nome das pessoas do arquivo, o comando usado será: 50 | * awk 'NR>1{print $1}' entrada.txt 51 | 52 | * Onde "NR>1" ignora a primeira linha, que neste caso é o cabeçalho, e $1 é o primeiro campo da linha que tem "espaço vazio" como parâmetro de separação. 53 | 54 | * Arquivo AWK 55 | * Há também uma outra forma de realizar esse processamento que é criando um arquivo awk e inserindo nele os comandos necessários para realizar tal tarefa. 56 | * O arquivo pode ser feito utilizando o "BEGIN" e o "END" que são comandos utilizados 'antes' de processar e 'depois' de processar o arquivo. 57 | 58 | ### Exemplo: 59 | ``` awk 60 | BEGIN { "condições e comandos a serem executados antes de iniciar a leitura do arquivo" } 61 | { 62 | "condições e comandos a serem executados em cada linha do arquivo" 63 | } 64 | END { "comandos a serem executados após a leitura do arquivo" } 65 | ``` 66 | 67 | # Videoaula(s) 68 | 69 | * AWK: https://youtu.be/mTlx7Cz7y2I?list=PLlfnoloSCPI2yAhYzUXE6V8-8DNC5nk0M 70 | 71 | -------------------------------------------------------------------------------- /13-AWK/exemplos/alunos.txt: -------------------------------------------------------------------------------- 1 | José das Mercês Augusto, 2051241022,Engenharia 2 | Raissa Almeida de Souza, 205371042,Redes de Computadores 3 | Ângelo Souza, 20544201302,Engenharia 4 | Hiroyuki Takashi Nagasawa Silva, 201430421,Estética 5 | Tarcísio Albuquerque Queiroz Smith, 2042451032,Música 6 | Amanda Soares da Silva Ferreira, 2010413202,Artes 7 | Expedito Mendes Oliveira Santos, 2041231041,Engenharia 8 | Sérgio Berranteiro Jaguar Hunter, 203324102,Meio Ambiente 9 | -------------------------------------------------------------------------------- /13-AWK/exemplos/cursos.awk: -------------------------------------------------------------------------------- 1 | #IMPRIMINDO APENAS OS CURSOS DA LISTA ALUNOS.TXT 2 | BEGIN { FS=","; print "Cursos dos alunos: \n" } 3 | { 4 | print $NF 5 | } 6 | END { print "\nFim do arquivo" } 7 | 8 | #FS CONSIDERA "," COMO SEPARADOR DE CAMPOS 9 | #$NF É O ÚLTIMO CAMPO DA LINHA. 10 | #OBS: É necessário digitar na linha de comandos o comando: awk -f curso.awk alunos.txt 11 | -------------------------------------------------------------------------------- /13-AWK/exemplos/matriculas.sh: -------------------------------------------------------------------------------- 1 | #EXEMPLO DE COMO EXECUTAR O COMANDO PARA IMPRIMIR APENAS AS MATRÍCULAS DO ARQUIVO ALUNOS.TXT 2 | 3 | awk -F "," '{print $2}' alunos.txt 4 | -------------------------------------------------------------------------------- /13-AWK/exemplos/nomes.awk: -------------------------------------------------------------------------------- 1 | #A presença do BEGIN e do END não são obrigatórias, o comando funciona da mesma forma. 2 | #OBS: É necessário digitar na linha de comandos o comando: awk -f nomes.awk alunos.txt 3 | 4 | { 5 | print $1 6 | } 7 | -------------------------------------------------------------------------------- /13-AWK/exercicios/atividades.md: -------------------------------------------------------------------------------- 1 | ### Exercícios 2 | 3 | * Levando em consideração o arquivo servicos.txt crie um ARQUIVO awk que imprima: "Serviço dos funcionários:" e liste abaixo todos os serviços 4 | -------------------------------------------------------------------------------- /13-AWK/exercicios/diasdetrabalho.md: -------------------------------------------------------------------------------- 1 | ### Exercícios 2 | 3 | * Levando em consideração o arquivo servicos.txt crie um ARQUIVO awk que imprima: 4 | * "Funcionários e dias de trabalho:" e em seguida imprima o nome dos funcionários e os dias em que eles trabalharão. 5 | -------------------------------------------------------------------------------- /13-AWK/exercicios/nomes.md: -------------------------------------------------------------------------------- 1 | ### Exercícios 2 | 3 | * Levando em consideração o arquivo servicos.txt use um comando awk (não precisa criar um arquivo) para listar APENAS os nomes dos funcionários 4 | -------------------------------------------------------------------------------- /13-AWK/exercicios/servicos.txt: -------------------------------------------------------------------------------- 1 | Nome , Dia , Atividade 2 | José Ailton, Segunda - Terça e Quarta, Manutenção dos computadores 3 | Maria Joaquina da Silva, Quarta e Sexta-feira, Imprimir documentos 4 | Saulo de Tarso Oliveira, Quinta e Sábado, Checagem dos documentos 5 | Rebeca Sales da SIlva Santos, Terça e Quinta, Monitorar a rede 6 | João Quebec Souza, Domingo, Backup do Servidor 7 | Silvandro Ardones Costa, Segunda a Sexta, Verificar Conexão da rede 8 | Júlia Sobrinho, Quarta e Sexta, Criar planilhas no Excel 9 | Pietro Jackson Ferreira, Sábado, Distribuição dos Arquivos 10 | -------------------------------------------------------------------------------- /14-SED/README.md: -------------------------------------------------------------------------------- 1 | # SED 2 | 3 | * Assim como o AWK, o SED é um comando usado principalmente para a manipulação de arquivo, a principal diferença é: o SED utiliza apenas expressões regulares. 4 | 5 | * O comando é formado basicamente por: sed 'expressão' arquivo 6 | 7 | * Opções do comando SED: 8 | * -i: Altera o arquivo; 9 | * -e: Imprime na tela, mas não altera o arquivo; 10 | * s: Substitui um trecho do texto por outro; 11 | * !: Inverte a lógica do comando; 12 | * ;:Separador de comandos; 13 | * |: Separador de strings; 14 | * d: Usado para deletar; 15 | * p: Usado para imprimir (geralmente utilizado quando se usa o -n); 16 | * g: Trata a linha inteira; 17 | * q: Sai do SED após executar o comando; 18 | 19 | 20 | ### Exemplos 21 | ```bash 22 | echo "Bem-vindo ao Linux! Só o Linux é Linux" | sed 's/Linux/Windows/' 23 | ``` 24 | 25 | * A saída deste comando será: "Bem-vindo ao Windows! Só o Linux é Linux", pois a expressão descrita no sed faz a primeira alteração e já passa para a outra linha, caso queiramos alterar a linha inteira, basta adicionar a opção "g" ao final: 26 | * echo "Bem-vindo ao Linux! Só o Linux é Linux" | sed 's/Linux/Windows/g' 27 | 28 | * Removendo as linhas do arquivo 29 | * Suponhamos que temos um arquivo ips.txt e que queremos remover as dez primeiras linhas do arquivos, o comando utilizado seria: 30 | ```bash 31 | sed '1,10 d' ips.txt 32 | ``` 33 | 34 | # Videoaula(s) 35 | 36 | * Comando SED: https://youtu.be/JaJny67jrqY?list=PLlfnoloSCPI2yAhYzUXE6V8-8DNC5nk0M 37 | 38 | -------------------------------------------------------------------------------- /14-SED/exemplos/ips.txt: -------------------------------------------------------------------------------- 1 | PC1 IP: 192.168.0.1 2 | PC2 IP: 192.168.0.2 3 | 4 | 5 | 6 | PC3 IP: 192.168.0.3 7 | 8 | 9 | 10 | PC4 IP: 192.168.0.4 11 | PC5 IP: 192.168.0.5 12 | PC6 IP: 192.168.0.6 13 | PC7 IP: 192.168.0.7 14 | 15 | 16 | PC8 IP: 192.168.0.8 17 | PC9 IP: 192.168.0.9 18 | 19 | PC10 IP: 192.168.0.10 20 | PC11 IP: 192.168.0.11 21 | PC12 IP: 192.168.0.12 22 | 23 | 24 | PC13 IP: 192.168.0.13 25 | PC14 IP: 192.168.0.14 26 | PC15 IP: 192.168.0.15 27 | PC16 IP: 192.168.0.16 28 | 29 | 30 | PC17 IP: 192.168.0.17 31 | PC18 IP: 192.168.0.18 32 | PC19 IP: 192.168.0.19 33 | PC20 IP: 192.168.0.20 34 | 35 | PC21 IP: 192.168.0.21 36 | PC22 IP: 192.168.0.22 37 | PC23 IP: 192.168.0.23 38 | PC24 IP: 192.168.0.24 39 | 40 | PC25 IP: 192.168.0.25 41 | PC26 IP: 192.168.0.26 42 | 43 | PC27 IP: 192.168.0.27 44 | 45 | PC28 IP: 192.168.0.28 46 | PC29 IP: 192.168.0.29 47 | PC30 IP: 192.168.0.30 48 | PC31 IP: 192.168.0.31 49 | PC32 IP: 192.168.0.32 50 | PC33 IP: 192.168.0.33 51 | PC34 IP: 192.168.0.34 52 | PC35 IP: 192.168.0.35 53 | PC36 IP: 192.168.0.36 54 | PC37 IP: 192.168.0.37 55 | PC38 IP: 192.168.0.38 56 | PC39 IP: 192.168.0.39 57 | PC40 IP: 192.168.0.40 58 | PC41 IP: 192.168.0.41 59 | PC42 IP: 192.168.0.42 60 | PC43 IP: 192.168.0.43 61 | PC44 IP: 192.168.0.44 62 | PC45 IP: 192.168.0.45 63 | PC46 IP: 192.168.0.46 64 | PC47 IP: 192.168.0.47 65 | PC48 IP: 192.168.0.48 66 | PC49 IP: 192.168.0.49 67 | PC50 IP: 192.168.0.50 68 | -------------------------------------------------------------------------------- /14-SED/exemplos/linha-em-branco.md: -------------------------------------------------------------------------------- 1 | ### Exemplo 2 | * Levando em consideração o arquivo ips.txt, para limpar todas as linhas em branco basta utilizar o comando: 3 | ``` bash 4 | sed -i '/^$/d' ips.txt 5 | ``` 6 | -------------------------------------------------------------------------------- /14-SED/exemplos/maquinas.txt: -------------------------------------------------------------------------------- 1 | PC1: Linux 2 | PC2: Windows 3 | PC3: macOS 4 | PC4: macOS 5 | PC5: macOS 6 | PC6: Windows 7 | PC7: Windows 8 | PC8: Windows 9 | PC9: Windows 10 | PC10: Windows 11 | -------------------------------------------------------------------------------- /14-SED/exemplos/mascara.md: -------------------------------------------------------------------------------- 1 | ### Exemplo 2 | * Levando em consideração o arquivo ips.txt, caso fosse necessário adicionar uma máscara padrão para todos os ips o comando seria: 3 | ``` bash 4 | sed -i 's/$/ Máscara: 255.255.255.0/' ips.txt 5 | ``` 6 | -------------------------------------------------------------------------------- /14-SED/exemplos/update.md: -------------------------------------------------------------------------------- 1 | ### Exemplos 2 | 3 | * Levando em consideração o arquivo maquinas.txt, caso fosse realizado um update na empresa e todos os PCS que possuíam Windows passassem a ser Linux, o comando utilizado para a modificação do arquivo seria: 4 | ``` bash 5 | sed -i 's/Windows/Linux/' maquinas.txt 6 | ``` 7 | 8 | * Onde o -i é a opção de alterar o arquivo, "s" é a opção de substituir uma palavra por outra. 9 | 10 | * Caso o update fosse geral e os PCS com Windows e macOS virassem PCS com Linux, o comando utilizado seria: 11 | ``` bash 12 | sed -i 's/Windows\|macOS/Linux/' maquinas.txt 13 | ``` 14 | 15 | * Caso o update fosse apenas nos 5 primeiros computadores e todos se tornassem Linux, o comando seria: 16 | ``` bash 17 | sed -i '1,5s/Windows\|macOS/Linux/' maquinas.txt 18 | ``` 19 | -------------------------------------------------------------------------------- /14-SED/exercicios/manutencao.md: -------------------------------------------------------------------------------- 1 | ### Exercício 2 | 3 | * Levando em consideração o arquivo redes.txt remova os 10 primeiros dispositivos do arquivo usando o comando sed 4 | -------------------------------------------------------------------------------- /14-SED/exercicios/mascara.md: -------------------------------------------------------------------------------- 1 | ### Exercícios 2 | 3 | * Levando em consideração o arquivo redes.txt, insira a máscara 255.255.0.0, usando SED, nos dispositivos que se encontram sem máscara. 4 | 5 | * Agora mude todas as máscaras para a máscara: 255.0.0.0 6 | -------------------------------------------------------------------------------- /14-SED/exercicios/redes.txt: -------------------------------------------------------------------------------- 1 | Rede 1: 192.168.1.0 2 | PC1: IP:192.168.1.1 3 | PC2: IP:192.168.1.2 4 | PC3: IP:192.168.1.3 5 | PC4: IP:192.168.1.4 6 | PC5: IP:192.168.1.5 7 | PC6: IP:192.168.1.6 8 | PC7: IP:192.168.1.7 9 | PC8: IP:192.168.1.8 10 | PC9: IP:192.168.1.9 11 | PC10: IP:192.168.1.10 12 | PC11: IP:192.168.1.11 13 | PC12: IP:192.168.1.12 14 | PC13: IP:192.168.1.13 15 | PC14: IP:192.168.1.14 16 | PC15: IP:192.168.1.15 17 | PC16: IP:192.168.1.16 18 | PC17: IP:192.168.1.17 19 | PC18: IP:192.168.1.18 20 | PC19: IP:192.168.1.19 21 | PC20: IP:192.168.1.20 22 | PC21: IP:192.168.1.21 23 | PC22: IP:192.168.1.22 24 | PC23: IP:192.168.1.23 25 | PC24: IP:192.168.1.24 26 | PC25: IP:192.168.1.25 27 | Rede 2: 192.168.5.0 28 | PC26: IP:192.168.5.26 Máscara: 255.255.255.0 29 | PC27: IP:192.168.5.27 Máscara: 255.255.255.0 30 | PC28: IP:192.168.5.28 Máscara: 255.255.255.0 31 | PC29: IP:192.168.5.29 Máscara: 255.255.255.0 32 | PC30: IP:192.168.5.30 Máscara: 255.255.255.0 33 | PC31: IP:192.168.5.31 Máscara: 255.255.255.0 34 | PC32: IP:192.168.5.32 Máscara: 255.255.255.0 35 | PC33: IP:192.168.5.33 Máscara: 255.255.255.0 36 | PC34: IP:192.168.5.34 Máscara: 255.255.255.0 37 | PC35: IP:192.168.5.35 Máscara: 255.255.255.0 38 | PC36: IP:192.168.5.36 Máscara: 255.255.255.0 39 | PC37: IP:192.168.5.37 Máscara: 255.255.255.0 40 | PC38: IP:192.168.5.38 Máscara: 255.255.255.0 41 | PC39: IP:192.168.5.39 Máscara: 255.255.255.0 42 | PC40: IP:192.168.5.40 Máscara: 255.255.255.0 43 | PC41: IP:192.168.5.41 Máscara: 255.255.255.0 44 | PC42: IP:192.168.5.42 Máscara: 255.255.255.0 45 | PC43: IP:192.168.5.43 Máscara: 255.255.255.0 46 | PC44: IP:192.168.5.44 Máscara: 255.255.255.0 47 | PC45: IP:192.168.5.45 Máscara: 255.255.255.0 48 | PC46: IP:192.168.5.46 Máscara: 255.255.255.0 49 | PC47: IP:192.168.5.47 Máscara: 255.255.255.0 50 | PC48: IP:192.168.5.48 Máscara: 255.255.255.0 51 | PC49: IP:192.168.5.49 Máscara: 255.255.255.0 52 | PC50: IP:192.168.5.50 Máscara: 255.255.255.0 53 | -------------------------------------------------------------------------------- /15-Interface gráfica/README.md: -------------------------------------------------------------------------------- 1 | # Interface gráfica no shell script usando o Yad 2 | 3 | 4 | * Para criar um tipo de interface gráfica em nossos scripts shell utilizaremos o yad que é uma ferramenta disponível no shell script do Linux que permite a criação de caixas de diálogo gráficas interativas. Ela pode ser usada para exibir informações, receber entrada do usuário e executar ações com base nas escolhas feitas. 5 | * O yad diferente do zenity (outra ferramenta de interface gráfica muito utilizada no linux) não vem instalado por padrão nos sistemas linux, então para instalar usaremos o seguinte comando: 6 | sudo apt install yad 7 | * caso queira verificar se o yad já foi instalado no linux, podemos digitar yad --version ou whereis yad. 8 | 9 | 10 | * Sintaxe 11 | * A estrutura das possíveis caixas de diálogo do yad é simples, é baseada apenas em: 12 | > yad "tipo de diálogo" "opções específicas do diálogo" 13 | 14 | 15 | ### Alguns Tipos de caixa de diálogo e opções específicas, para ver todos os tipos acessar o link do campo "Referências": 16 | 17 | 18 | * **--calendar** 19 | * Retorna a data escolhida. 20 | * Opções específicas: 21 | * --day="Dia": Especifica o dia que estará selecionado por padrão no calendário; 22 | * --month="Mês": Especifica o mês que estará selecionado por padrão no calendário; 23 | * --year="Ano": Especifica o ano que estará selecionado por padrão no calendário. 24 | * --date-format=PATTERN: Defina o formato para a data retornada. 25 | 26 | 27 | * **--text** 28 | * Opções de seleção de formulário 29 | * Opções específicas: 30 | * --text-info : Exibir diálogo de texto informativo 31 | * --fore=COR : Usar cor específica para o texto 32 | * --back=COR : Use cor específica no fundo 33 | * --wrap : Ativar quebra de texto 34 | * --justify=TIPO : Definir justificação (left, right, center ou fill) 35 | 36 | 37 | 38 | 39 | * **--entry** 40 | * Caixa de diálogo para inserir textos. 41 | * Opções específicas: 42 | * --entry-label=STRING: Defina o texto que aparecerá antes da caixa de input. 43 | * --entry-text=STRING : Define o texto de entrada inicial ou texto padrão da caixa de combinação. 44 | * --hide-text : Oculte o texto de entrada 45 | * --numeric : Caixa de entrada de dados com botão de rotação em vez da entrada de texto 46 | 47 | 48 | * **--file** 49 | * Seleção de arquivos. 50 | * Opções específicas: 51 | * --filename=Nome_do_arquivo : O nome do arquivo definido aparecerá selecionado 52 | * --file-selection : Alias para --file 53 | * --multiple : Permite a seleção de vários arquivos 54 | * --directory : Selecionar somente diretório 55 | * --file-filter="*.txt" : Mostra somente os arquivos que baterem com o filtro especificado 56 | * **--form** 57 | * Opções de formulário 58 | * Opções específicas: 59 | * --field="rótulo:tipo:opções" : Define um campo no formulário. O rótulo é o texto exibido ao lado do campo, o tipo especifica o tipo de campo (como text, password, file, etc.), e as opções são usadas para personalizar o campo 60 | * --field-separator="Separador" : Define o separador entre os campos no formulário. Por padrão, o separador é um espaço em branco, 61 | * --align=Tipo : Defina o alinhamento dos rótulos de campo (left, center ou right) 62 | * --columns=Número : Defina o número de colunas no formulário 63 | * --scroll : Fazer um formulário com rolagem 64 | 65 | 66 | * **--font** 67 | * Opções de seleção de font 68 | * Opções específicas: 69 | * --fontname=FONTNAME : Define a fonte do texto 70 | * --preview=TEXTO : Definir sequência de texto para visualização 71 | * --separate-output : Saída separada da descrição da fonte 72 | 73 | 74 | 75 | 76 | * **--list** 77 | * Opções de seleção de formulário 78 | * Opções específicas: 79 | * --column="rótulo" : Adiciona uma coluna com o rótulo especificado à lista. Você pode adicionar várias colunas, separando-as por vírgulas. 80 | * --text="texto": Define o texto a ser exibido acima da lista. 81 | * --separator="separador": Define o separador entre as colunas da lista. O padrão é uma guia. Por exemplo: 82 | * --print-column=N: Define o índice da coluna cujo valor será retornado ao selecionar uma opção. O valor será impresso na saída padrão. O índice da coluna começa em 1. 83 | 84 | 85 | ### Código de saída 86 | * O yad gera códigos de saída de acordo com o clique do usuário, cada clique representa um código, são eles: 87 | 88 | 89 | * Código de saída 0: O usuário clicou em "OK"; 90 | * Código de saída 1: O usuário clicou em "Cancelar" ou usou a janela para fechar o diálogo; 91 | * Código de saída 70: O diálogo foi fechado porque o tempo foi esgotado; 92 | * Código de saída 252:A caixa de diálogo foi fechada pressionando Esc ou usando as funções da janela para fechar a caixa de diálogo. 93 | 94 | 95 | ### Opções comuns 96 | * As opções comuns são as que irão editar a caixa de diálogo, são elas: 97 | * --title="título desejado" (opção referente ao título da caixa de diálogo) 98 | * --window-icon="caminho do ícone" (Altera o ícone exibido nas caixas de diálogo "info", "warning", "question" e "error") 99 | * --widith="largura" (Largura da caixa de diálogo) 100 | * --heigh="altura" (Altura da caixa de diálogo) 101 | * --timeout="tempo" (Especifica o tempo em segundos em que a caixa de diálogos será fechada) 102 | * --text-align=TYPE (Defina o tipo de justificação do texto da caixa de diálogo. TYPE pode ser esquerdo , direito , centralizado ou preenchido.) 103 | * --image=IMAGE (Defina a imagem da caixa de diálogo que aparece no lado esquerdo do texto da caixa de diálogo. IMAGE pode ser o nome do arquivo ou o nome do ícone do tema do ícone atual.) 104 | 105 | 106 | ## Exemplos 107 | * Os comandos do yad podem ser executados na própria linha de comando, você pode utilizar isto para realizar os seus testes. 108 | 109 | 110 | * Para criar um formulário e adicionar o nome e o número de um determinado usuário como entrada, basta utilizar o comando: 111 | > yad --form --title="Informações do usuário" --field="Nome:text" --field="Idade:num" --field="Comida favorita?:text" --field-separator="-" 112 | * Lembrando: O --field="Nome:text" é respectivamente a mensagem que irá aparecer na tela e o tipo, que nesse caso é text e o --separator="-" para que a saída seja separada por vírgula, ou seja, a saída será: "Nome", "Número". Por padrão a saída é separada por "|" 113 | 114 | 115 | * Lista de alunos e cursos do IFPB 116 | > yad --list --title="Alunos-cursos do IFPB" --column="Aluno" --column="Curso" --separator="," Mariana "Redes de computadores" Pedro Administração Paulo "Engenharia de software" Ana "Redes de computadores" 117 | 118 | 119 | 120 | 121 | ## Referências 122 | 123 | 124 | https://man.archlinux.org/man/extra/yad/yad.1.en 125 | http://www.dicas-l.com.br/arquivo/yad_yet_another_dialog.php 126 | -------------------------------------------------------------------------------- /15-Interface gráfica/exemplos/filtrar-arq.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #Exemplo de como filtrar a seleção de um arquivo no yad 3 | 4 | file=$(yad --title="Selecione o arquivo desejado" --file --file-filter="*.txt") 5 | 6 | case $? in 7 | 0) 8 | linhas=$(cat $file | wc -l) 9 | yad --text "O arquivo:$file possui $linhas linhas. " 10 | ;; 11 | 1) 12 | yad --text "Programa encerrado!" 13 | ;; 14 | esac 15 | -------------------------------------------------------------------------------- /15-Interface gráfica/exemplos/form-curso.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #Exemplo de form com yad 3 | 4 | opc=$(yad --form --title "Exemplo de form" \ 5 | --text "Informe seus dados referentes ao seu curso" \ 6 | --field "Informe seu nome completo:text" \ 7 | --field "Escolha o seu curso:CB" \ 8 | --field "Em qual período vc está?:NUM" \ 9 | --field "Selecione o seu currículo:FL" \ 10 | "" \ 11 | 'Redes de Computadores!Sistema para Internet!Engenharia elétrica!Administração' \ 12 | ) 13 | 14 | 15 | case $? in 16 | 0) 17 | usuario=$(echo "$opc" | cut -d "|" -f1) 18 | yad --text "Suas informações foram salvas $usuario!" 19 | ;; 20 | 1) 21 | yad --text "Formulário encerrado!" 22 | ;; 23 | esac 24 | -------------------------------------------------------------------------------- /15-Interface gráfica/exercícios/arquivos.md: -------------------------------------------------------------------------------- 1 | * Crie um script com interface gráfica que salve em uma variável o caminho de **MÚLTIPLOS** arquivos selecionados pelo usuário. -------------------------------------------------------------------------------- /15-Interface gráfica/exercícios/forms.md: -------------------------------------------------------------------------------- 1 | * Crie um script com interface gráfica com um formulário com as seguintes entradas: Nome, Sobrenome, Idade, Matrícula, CPF e Telefone. -------------------------------------------------------------------------------- /15-Interface gráfica/exercícios/usuarios.md: -------------------------------------------------------------------------------- 1 | * Crie um script com interface gráfica que peça para o usuário inserir o seu "usuário" e "senha" e salve o o usuário em uma variável e a senha em outra variável. 2 | 3 | 4 | * Melhore o script para que quando o usuário insira o usuário e senha ele entre em um formulário que possua as seguintes entradas: Nome, Telefone, CPF e Data de nascimento. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ShellScript 2 | 3 | Repositório da disciplina Programação de Scripts do curso de Redes de Computadores 4 | --------------------------------------------------------------------------------