Last active
March 13, 2018 18:39
-
-
Save elder/c10480171c4b84b131568f529b91d807 to your computer and use it in GitHub Desktop.
Define a função calc, que permite executar cálculos simples no terminal linux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Faz o cálculo de uma expressão matemática. A precisão é de duas casas decimais, | |
# por default. Mas é possível alterar isso com a opção -p/--precision. Trata-se de | |
# uma calculadora simples e bastante útil para o terminal do Linux. | |
function calc () | |
{ | |
local OPTIONS | |
local -r SHORT_OPTIONS="p:h" | |
local -r LONG_OPTIONS="precision:,help" | |
local PRECISION=2 | |
calc_usage () { echo 1>&2 "Uso: $1 [-p|--precision PRECISAO] EXPRESSÃO"; } | |
# Nenhum parâmetro foi passado, não há o que fazer | |
if [ $# -eq 0 ]; then | |
calc_usage "$FUNCNAME" | |
return 1 | |
fi | |
OPTIONS=$(getopt --name "$FUNCNAME" \ | |
--options "$SHORT_OPTIONS" \ | |
--longoptions "$LONG_OPTIONS" -- "$@") | |
test $? -ne 0 && return 1 | |
eval set -- "$OPTIONS" | |
while true; do | |
case "$1" in | |
-p|--precision) | |
PRECISION=$2 | |
shift 2 | |
;; | |
-h|--help) | |
calc_usage "$FUNCNAME" | |
return 0 | |
;; | |
--) | |
shift | |
break | |
;; | |
*) | |
break | |
;; | |
esac | |
done | |
test $# -eq 0 && { calc_usage "$FUNCNAME"; return 1; } | |
# Efetua o cálculo e imprime na tela | |
awk -v precision=$PRECISION \ | |
'BEGIN { result = '"$*"'; printf "%." precision "f\n", result; exit }' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment