Skip to content

Instantly share code, notes, and snippets.

@diogocapela
Last active November 20, 2017 19:58
Show Gist options
  • Save diogocapela/eaca81660ea23ae4d01a4947b8ebb6a1 to your computer and use it in GitHub Desktop.
Save diogocapela/eaca81660ea23ae4d01a4947b8ebb6a1 to your computer and use it in GitHub Desktop.

how to run

# touch teste.sh

# nano teste.sh

# chmod u+x teste.sh

# ./teste.sh

# ITERATIONS: FOR

#!/bin/bash
for n in 1 2 3 4 10 20
do
  echo $((n * 2))
done

# ITERATIONS: WHILE

#!/bin/bash
n=1
while [ $n -le 100 ]
do
  echo $(($n * 2))
  n=$(($n+1))
done

# ITERATIONS: UNTIL

#!/bin/bash

if [ $# -ne 1 ]
  then exit 1
fi
until who | cut -d' ' -f1 | grep "^$1$" > "/dev/null"
do
  sleep 3
# programa para por 3 segundos
  echo "user $1 offline!"
done
  echo "user $1 online!"
exit 0 
# o programa terminou sem problemas nenhuns se tiver um 0, se tiver um numero estamos a sinalizar um erro, o valor do exit é uma variavel para erro

# ITERATIONS: FUNCTIONS

#!/bin/bash

function mult2numbers() {

  local minhaConstante = "const" # constante scoped
  local readonly name="mult2numbers" # function scoped variable

  # o $# é uma variavel onde está a quantidade de parametros passados para a funcão
  # não é preciso definir os parametros na funcao

  if [ $# -ne 2 ]
    then echo "error in $name"
    exit 1
  fi

  echo $1 '*' $2 '=' $(($1 * $2))
}


previous=0
for n in 1 2 3 4 5 6 7 8 9 10; do
 mult2numbers $previous $n
 previous=$n
done

Useful Shell scripting tips

– break: immediately leave a cycle (for, while, until) – continue: go immediately to the next cycle iteration – exit: immediately terminate a script – clear: clear the screen – export: create a persistent environment variable – arithmetic operations: $(($var1 op $var2)) • op may be + - * / **[power] %[modulo] • increment a variable: n=$(($n+1)) • decrement a variable: n=$(($n-1))

#!/bin/bash
echo 'exam result?'
read answer
// o ; é para separar, podemos dar um enter e por o then la em baixo
if [ "$answer" = 'yes' ]; then
echo 'sucessful'
elif [ "$answer" = 'no' ]; then
echo 'UUUU'
else
echo 'unsucessful'
fi
#!/bin/bash
echo 'exam??'
read answer
// aqui o ;; é o break, duplo ; significa break
case "$answer" in
'yes' | 'y') echo 'sucess' ;;
'no' | 'n' ) echo 'fail' ;;
* ) echo 'ukown' ;;
esac
string1 // true if string is not empty
string1 = string2 // true if strings are equal
string1 != string2 // true if strings are dif
-n string1 // true if string is not null
-z stirng1 // true if string is null
expressoes operation:
exp1 -op exp2 //
// op can be:
-eq // comparação de valors numericos inteiros "012" -eq "12 " é true
-ne
-gt
-ge
-lt
-le
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment