A primeira linha do script é o shebang que informa ao sistema como executar.
#!/usr/bin/env bashExemplo simples de Hello world!:
echo Hello world! # => Hello world!Cada comando começa em uma nova linha ou após um ponto e vírgula:
echo 'This is the first line'; echo 'This is the second line'
# => This is the first line
# => This is the second line
echo -e "START OF FILE\n$Contents\nEND OF FILE" # break line \nDeclarar uma variável fica assim:
Variable="Some string"
Variable = "Some string" # "Variable: command not found"Usando a variável:
echo $Variable # => Some string
echo "$Variable" # => Some string
echo '$Variable' # => $VariableParameter expansion
echo ${Variable} # => Some string
# Este é um uso simples de expansão de parâmetros Parameter Expansion obtém um valor de uma variável. Ele "expande" ou imprime o valor. Durante o tempo de expansão o valor ou parâmetro pode ser modificado.
echo ${Variable/Some/A} # Isso substituirá a primeira ocorrência de "Some" por "A"Substring de uma variável
Length=7
# retorna apenas os primeiros 7 caracteres
echo ${Variable:0:Length} # => Some st
echo ${Variable: -5} # => tring
echo ${#Variable} # => 11 | string length (#Variable)Indirect expansion
OtherVariable="Variable"
echo ${!OtherVariable} # => Some StringValor padrão para variável
# => DefaultValueIfFooIsMissingOrEmpty
echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"}
# Isso funciona para null (Foo=) e string vazia (Foo=""); zero (Foo=0) retorna 0. Retorna apenas o valor padrão e não altera o valor da variável.Arrays
# Declare an array with 6 elements
array0=(one two three four five six)
# Print first element
echo $array0 # => "one"
echo ${array0[0]} # => "one"
# Print all elements
echo ${array0[@]} # => "one two three four five six"
# Print number of elements
echo ${#array0[@]} # => "6"
# Print number of characters in third element
echo ${#array0[2]} # => "5"
# Print 2 elements starting from fourth
echo ${array0[@]:3:2} # => "four five"
# Print all elements. Each of them on new line.
for i in "${array0[@]}"; do
echo "$i"
doneBrace Expansion
# Used to generate arbitrary strings
echo {1..10} # => 1 2 3 4 5 6 7 8 9 10
echo {a..z} # => a b c d e f g h i j k l m n o p q r s t u v w x y zBuilt-in variables
echo "Last program's return value: $?"
echo "Script's PID: $$"
echo "Number of arguments passed to script: $#"
echo "All arguments passed to script: $@"
echo "Script's arguments separated into different variables: $1 $2..."Comandos
echo "I'm in $(pwd)"
echo "I'm in $PWD"
clear # `clear` limpa a tela
# Um único & depois que um comando o executa em segundo plano
sleep 30 &
jobs # => [1]+ Running sleep 30 &
kill %2 # kill jobLer input
echo "What's your name?"
read Name
echo Hello, $Name!Condições
if [ "$Name" != $USER ] # "$Name" é safe syntax > if [ "" != $USER ]
then
echo "Your name isn't your username"
else
echo "Your name is your username"
fi
# outras condicionais
echo "Always executed" || echo "Only executed if first command fails"
echo "Always executed" && echo "Only executed if first command does NOT fail"
# Para usar && e || com o if, precisa abrir os pares de colchetes
if [ $Nome == "Estevao"] && [ $Idade -eq 15]
then
echo "Isso vai rodar se $Nome é igual Estevao E $Idade é 15."
fi
fi [ $Nome == "Daniela" ] || [ $Nome = "Jose" ]
then
echo "Isso vai rodar se $Nome é Daniela ou Jose."
fiRegex
Email=me@example.com
if [[ "$Email" =~ [a-z]+@[a-z]{2,}\.(com|net|org) ]]
then
echo "Valid email!"
fiAlias
alias ping='ping -c 5' # cria um alias
\ping 192.168.1.1 # executa ping -c 5 192.168.1.1
alias -p # print aliasExpressões
echo $(( 10 + 5 )) # => 15Listagens
# Shell trabalha no contexto atual, logo um ls irá mostrar o que tem no diretório do script
ls
ls -l # sepado por linhas e informações de r/w
ls -t # sorting last-modified
ls -R # lista recursivamente subdiretórios
ls | wc -l # mostra o número de arquivos e diretórios
echo "There are `ls | wc -l` items here."
echo "There are $(ls | wc -l) items here."Pipeline
# Criar filtros para string via padrões
ls -l | grep "\.txt"Cat
# imprime o stdout de arquivos
cat file.txt
Contents=$(cat file.txt) # como expressãoCp
# copia o conteúdo de um lugar para outro, pode reescrever
cp srcFile.txt clone.txt
cp -r srcDirectory/ dst/ # copia diretórios e arquivos recursivamenteMv
# mover algo de um lugar para outro
mv s0urc3.txt dst.txtCd
cd ~ # vai pra home
cd # also vai pra home
cd .. # volta um diretório
cd - # volta pro último diretório que estava
(echo "I'm here: $PWD") && (cd someDir; echo "Then, I'm here: $PWD")Mkdir
# cria um diretório
mkdir myNewDir
mkdir -p myNewDir/with/intermediate/directories # cria caso não existeRedirection operator
# Redirecionar o comando de input e output (stdin, stdout e stderr).
# Lê o stdin até EOF e sobrescreve hello.py com as linhas entre "EOF".
# Copia o ouput para hello.py
cat > hello.py << EOF
#!/usr/bin/env python
from __future__ import print_function
import sys
print("#stdout", file=sys.stdout)
print("#stderr", file=sys.stderr)
for line in sys.stdin:
print(line, file=sys.stdout)
EOFRm
# remover arquivos e diretórios
rm -v output.out error.err output-and-error.log
rm -r tempDir/ # recursively deleteOperador switch case
# condicional switch case
case "$Variable" in
0) echo "There is a zero.";;
1) echo "There is a one.";;
*) echo "It is not null.";; # match everything
esacFor loops
for Variable in {1..3}
do
echo "$Variable" # >> 1 2 3
done
# -----------------------------
for ((a=1; a <= 3; a++))
do
echo $a # >> 123
done
# -----------------------------
for Variable in file1 file2
do
cat "$Variable"
done
# -----------------------------
for Output in $(ls)
do
cat "$Output"
done
# -----------------------------
for Output in ./*.markdown
do
cat "$Output"
doneWhile
while [ true ]
do
echo "loop body here..."
break
doneFunctions
function foo ()
{
echo "Arguments work just like script arguments: $@"
echo "And: $1 $2..."
echo "This is a function"
value=0
return $value
}
foo arg1 arg2
foo "My name is" $NameTail
# prints last 10 lines of file.txt
tail -n 10 file.txtHead
# prints first 10 lines of file.txt
head -n 10 file.txtSort
# print file.txt's lines in sorted order
sort file.txtUniq
# report or omit repeated lines, with -d it reports them
uniq -d file.txtCut
# prints only the first column before the ',' character
cut -d ',' -f 1 file.txtSed/Grep
# -i: overwrite file
sed -i 's/okay/great/g' file.txt # replace 'okay' with 'great'
# print stdout todas as linhas q começa com 'foo' e terminam com 'bar'
grep "^foo.*bar$" file.txt
grep -r "^foo.*bar$" someDir/ # recursively `grep`
grep -n "^foo.*bar$" file.txt # give line numbers
grep -rI "^foo.*bar$" someDir/ # recursively `grep`, ignore binary
# filtrar por 'foo' terminado em 'bar' que contenham 'baz'
grep "^foo.*bar$" file.txt | grep -v "baz"Fgrep (grep -F)
# buscar um valor específico sem padrão
fgrep "foobar" file.txt
fgrep $1 $HOME/.zsh_history | sed "s/[:0-9:0;]*//g;s/^ *//"Trap
# O `trap` permite executar um comando sempre que recebe um sinal
trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM # rm if sigHelp
help
help help
help for
help return
help source
help .Man documentation
apropos bash
man 1 bash
man bash
# Read info documentation with `info` (`?` for help)
apropos info | grep '^info.*('
man info
info info
info 5 info
# Read bash info documentation:
info bash
info bash 'Bash Features'
info bash 6
info --apropos bashMore
- [[regex]]
- [[awk]]
- [[sed]]
- [[tr]]
- [[tee]]