├── bashsrc.png
├── src
├── os.sh
├── log.sh
├── rand.sh
├── cpu.sh
├── error.sh
├── grp.sh
├── mem.sh
├── json.sh
├── setup.sh
├── user.sh
├── time.sh
├── map.sh
├── path.sh
├── struct.sh
├── ps.sh
├── getopt.sh
├── textutil.sh
├── array.sh
├── regex.sh
├── net.sh
├── http.sh
├── string.sh
└── ssh.sh
├── README.md
└── bin
└── bashsrc
/bashsrc.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shellscriptx/bashsrc/HEAD/bashsrc.png
--------------------------------------------------------------------------------
/src/os.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Copyright 2018 Juliano Santos [SHAMAN]
4 | #
5 | # This file is part of bashsrc.
6 | #
7 | # bashsrc is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # bashsrc is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with bashsrc. If not, see .
19 |
20 | [ -v __OS_SH__ ] && return 0
21 |
22 | readonly __OS_SH__=1
23 |
24 | source builtin.sh
25 |
26 | # .FUNCTION os.uname -> [bool]
27 | #
28 | # Obtém informações sobre o kernel atual.
29 | #
30 | function os.uname()
31 | {
32 | getopt.parse 1 "uts:map:$1" "${@:2}"
33 |
34 | local __kernel__=/proc/sys/kernel
35 | local -n __ref__=$1
36 |
37 | __ref__=() || return 1
38 |
39 | __ref__[sysname]=$(< $__kernel__/ostype)
40 | __ref__[nodename]=$(< $__kernel__/hostname)
41 | __ref__[release]=$(< $__kernel__/osrelease)
42 | __ref__[version]=$(< $__kernel__/version)
43 | __ref__[domainname]=$(< $__kernel__/domainname)
44 | __ref__[machine]=$(arch)
45 |
46 | return $?
47 | }
48 |
49 | # .MAP uts
50 | #
51 | # Chaves:
52 | #
53 | # sysname
54 | # nodename
55 | # release
56 | # version
57 | # domainname
58 | # machine
59 | #
60 |
61 | # Função (somente leitura)
62 | readonly -f os.uname
63 |
64 | # /* __OS_SH__ */
65 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## bashsrc 2.0.0
2 |
3 | 
4 |
5 | ### Sobre
6 |
7 | O **bashsrc** é um projeto _open source_ distribuído em uma coleção de bibliotecas desenvolvidas em **shell script**, com um conjunto de funções úteis que fornece ao desenvolvedor um estilo de programação funcional com implementação de "tipos".
8 |
9 | O foco principal é a compatibilidade com o interpretador de comandos **BASH 4.3.0 (ou superior)**, cuja funções são desenvolvidas utilizando apenas recursos `built-in` e `coreutils`, evitando a utilização de dependências de pacotes externos que geram ‘coprocs’ durante a execução. Porém alguns critérios serão levados em consideração para tal aplicação: _desempenho, viabilidade, compatibilidade, distribuição da dependência_ entre outros, ficando de responsabilidade do desenvolvedor verificar e reportar tais dependências se houverem.
10 |
11 | ### Dependência
12 |
13 | |Pacote|Versão|Descrição|
14 | |-|-|-|
15 | |bash|4.3 (ou superior)|Interpretador de comandos BASH (Bourne-Again Shell).|
16 |
17 | ### Documentação
18 |
19 | A documentação padrão está disponível no arquivo fonte de cada biblioteca e que pode ser acessada pela utilitário [bashsrc](https://github.com/shellscriptx/bashsrc/wiki/Utilit%C3%A1rio) via linha de comando e distribuída junto ao projeto.
20 |
21 |
22 | **Para mais informações:** [clique aqui](https://github.com/shellscriptx/bashsrc/wiki)
23 |
24 | ### Reportando falhas
25 |
26 | * E-mail: shellscriptx@gmail.com
27 |
28 | ### Desenvolvedor
29 |
30 | * Juliano Santos [(SHAMAN)](https://t.me/x_SHAMAN_x)
31 |
32 | ### Comunidades
33 |
34 | * [Telegram (grupo)](https://t.me/shellscript_x)
35 |
36 | * [Facebook (fanpage)](https://fb.com/shellscriptx)
37 |
38 | * [Facebook (grupo)](https://fb.com/groups/shellscriptx)
39 |
40 | * [Blog](https://www.shellscriptx.blogspot.com.br)
41 |
42 | ### Gostaria de contribuir com o projeto? [clique aqui](https://www.padrim.com.br/apoiar?projeto_id=4707)
43 |
44 | 
45 |
--------------------------------------------------------------------------------
/src/log.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Copyright 2018 Juliano Santos [SHAMAN]
4 | #
5 | # This file is part of bashsrc.
6 | #
7 | # bashsrc is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # bashsrc is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with bashsrc. If not, see .
19 | #
20 |
21 | [ -v __LOG_SH__ ] && return 0
22 |
23 | readonly __LOG_SH__=1
24 |
25 | # .FUNCTION log.open ... -> [bool]
26 | #
27 | # Grava no arquivo o log com o formato e argumentos especificados.
28 | #
29 | function log.open()
30 | {
31 | getopt.parse -1 "file:str:$1" "fmt:str:$2" "args:str:$3" ... "${@:4}"
32 |
33 | local fmt
34 |
35 | if [ -d "$1" ]; then
36 | error.fatalf "'%s' é um diretório\n" "$1"
37 | elif [ -e "$1" -a ! -w "$1" ]; then
38 | error.fatalf "'%s' permissão negada\n" "$1"
39 | fi
40 |
41 | printf -v fmt '%s: %(%d/%m/%Y %H:%M:%S)T' "${0##*/}"
42 | printf "%s: $2\n" "$fmt" "${@:3}" >> "${1:-/dev/null}" 2>/dev/null ||
43 | error.errorf "'%s' formato inválido\n" "$2"
44 |
45 | return $?
46 | }
47 |
48 | # .FUNCTION log.new -> [bool]
49 | #
50 | # Cria e define as configurações do objeto log.
51 | #
52 | function log.new()
53 | {
54 | getopt.parse 3 "log:log_t:$1" "file:str:$2" "fmt:str:$3" "${@:4}"
55 |
56 | printf -v $1 '%s|%s' "${@:2}"
57 | return $?
58 | }
59 |
60 | # .FUNCTION log.write -> [bool]
61 | #
62 | # Grava as informações no log.
63 | #
64 | function log.write()
65 | {
66 | getopt.parse -1 "log:log_t:$1" "args:str:$2" ... "${@:3}"
67 |
68 | local __opts__
69 | IFS='|' read -ra __opts__ <<< "${!1}"
70 | log.open "${__opts__[@]}" "${@:2}"
71 | return $?
72 | }
73 |
74 | # .TYPE log_t
75 | #
76 | # Implementa o objeto 'S' com os métodos:
77 | #
78 | # S.new
79 | # S.write
80 | #
81 | typedef log_t log.new \
82 | log.write
83 |
84 | # Funções (somente-leitura)
85 | readonly -f log.open \
86 | log.new \
87 | log.write
88 | # /* __LOG_SH__ */
89 |
--------------------------------------------------------------------------------
/src/rand.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Copyright 2018 Juliano Santos [SHAMAN]
4 | #
5 | # This file is part of bashsrc.
6 | #
7 | # bashsrc is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # bashsrc is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with bashsrc. If not, see .
19 |
20 | [ -v __RAND_SH__ ] && return 0
21 |
22 | readonly __RAND_SH__=1
23 |
24 | source builtin.sh
25 |
26 | # .FUNCTION rand.random -> [uint]|[bool]
27 | #
28 | # Gera um inteiro pseudo-aleatório entre 0 e 32767.
29 | #
30 | function rand.random()
31 | {
32 | getopt.parse 0 "$@"
33 | echo $RANDOM
34 | return $?
35 | }
36 |
37 | # .FUNCTION rand.range -> [int]|[bool]
38 | #
39 | # Retorna um número inteiro pseudo-aleatório
40 | # dentro do intervalo especificado.
41 | #
42 | function rand.range()
43 | {
44 | getopt.parse 2 "min:int:$1" "max:int:$2" "${@:3}"
45 |
46 | shuf -i $1-$2 -n1
47 | return $?
48 | }
49 |
50 | # .FUNCTION rand.choice -> [str]|[bool]
51 | #
52 | # Escolhe um elemento aleatório de uma sequência.
53 | #
54 | function rand.choice()
55 | {
56 | getopt.parse 1 "list:array:$1" "${@:2}"
57 |
58 | local -n __ref__=$1
59 | local __list__
60 |
61 | [[ ${__ref__[@]} ]] &&
62 | __list__=("${__ref__[@]}") &&
63 | echo "${__list__[$(shuf -i 0-$((${#__list__[@]}-1)) -n1)]}"
64 |
65 | return $?
66 | }
67 |
68 | # .FUNCTION rand.shuffle -> [bool]
69 | #
70 | # Embaralha os elementos da lista.
71 | #
72 | function rand.shuffle()
73 | {
74 | getopt.parse 1 "list:array:$1" "${@:2}"
75 |
76 | local -n __ref__=$1
77 | mapfile $1 < <(printf '%s\n' "${__ref__[@]}" | shuf)
78 | return $?
79 | }
80 |
81 | # .TYPE rand_t
82 | #
83 | # Implementa o objeto 'S' com os métodos:
84 | #
85 | # S.choice
86 | # S.shuffle
87 | #
88 | typedef rand_t rand.choice \
89 | rand.shuffle
90 |
91 | # Funções (somente-leitura)
92 | readonly -f rand.random \
93 | rand.range \
94 | rand.choice \
95 | rand.shuffle
96 |
97 | # /* __RAND_SH__ */
98 |
--------------------------------------------------------------------------------
/src/cpu.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Copyright 2018 Juliano Santos [SHAMAN]
4 | #
5 | # This file is part of bashsrc.
6 | #
7 | # bashsrc is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # bashsrc is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with bashsrc. If not, see .
19 |
20 | [ -v __CPU_SH__ ] && return 0
21 |
22 | readonly __CPU_SH__=1
23 |
24 | source builtin.sh
25 |
26 | # .FUNCTION cpu.getinfo -> [bool]
27 | #
28 | # Obtem informações do processador,
29 | #
30 | # == EXEMPLO ==
31 | #
32 | # source cpu.sh
33 | #
34 | # # Inicializa o map
35 | # declare -A info=()
36 | #
37 | # # Obtendo informações.
38 | # cpu.getinfo info
39 | #
40 | # # Listando informações.
41 | # echo ${info[processor[0]]}
42 | # echo ${info[model_name[0]]}
43 | # echo ${info[cpu_mhz[0]]}
44 | # echo ---
45 | # echo ${info[processor[1]]}
46 | # echo ${info[model_name[1]]}
47 | # echo ${info[cpu_mhz[1]]}
48 | #
49 | # == SAÍDA ==
50 | #
51 | # 0
52 | # Intel(R) Core(TM) i5-3330 CPU @ 3.00GHz
53 | # 1961.110
54 | # ---
55 | # 1
56 | # Intel(R) Core(TM) i5-3330 CPU @ 3.00GHz
57 | # 1875.432
58 | #
59 | function cpu.getinfo()
60 | {
61 | getopt.parse 1 "cpuinfo:map:$1" "${@:2}"
62 |
63 | local __flag__ __value__ __info__
64 | local __i__=-1
65 | local -n __ref__=$1
66 |
67 | # Inicializar.
68 | __ref__=() || return 1
69 |
70 | while IFS=':' read __flag__ __value__; do
71 | __flag__=${__flag__//@($'\t')}
72 | __flag__=${__flag__// /_}
73 | __flag__=${__flag__,,}
74 | __value__=${__value__##+( )}
75 | case $__flag__ in
76 | processor) ((++__i__));;
77 | '') continue;;
78 | esac
79 | # Atribui o valor da chave.
80 | __ref__[$__flag__[$__i__]]=$__value__
81 | done < /proc/cpuinfo || error.error "'/proc/cpuinfo' não foi possível ler o arquivo"
82 |
83 | return $?
84 | }
85 |
86 | # .MAP cpuinfo
87 | #
88 | # Chaves:
89 | #
90 | # address_sizes[N]
91 | # apicid[N]
92 | # bogomips[N]
93 | # bugs[N]
94 | # cache_alignment[N]
95 | # cache_size[N]
96 | # clflush_size[N]
97 | # core_id[N]
98 | # cpu_cores[N]
99 | # cpu_family[N]
100 | # cpuid_level[N]
101 | # cpu_mhz[N]
102 | # flags[N]
103 | # fpu[N]
104 | # fpu_exception[N
105 | # initial_apicid[N]
106 | # microcode[N]
107 | # model[N]
108 | # model_name[N]
109 | # physical_id[N]
110 | # power_management[N]
111 | # processor[N]
112 | # siblings[N]
113 | # stepping[N]
114 | # vendor_id[N]
115 | # wp[N]
116 | #
117 | # > 'N' é o índice do elemento.
118 | #
119 |
120 | readonly -f cpu.getinfo
121 |
122 | # /* _CPU_SH__ */
123 |
--------------------------------------------------------------------------------
/src/error.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Copyright 2018 Juliano Santos [SHAMAN]
4 | #
5 | # This file is part of bashsrc.
6 | #
7 | # bashsrc is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # bashsrc is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with bashsrc. If not, see .
19 |
20 | [ -v __ERROR_SH__ ] && return 0
21 |
22 | readonly __ERROR_SH__=1
23 |
24 | source builtin.sh
25 |
26 | # .FUNCTION error.fatal -> [str]|[bool]
27 | #
28 | # Retorna uma mensagem de erro e finaliza o script com status '1'.
29 | #
30 | function error.fatal()
31 | {
32 | getopt.parse 1 "error:str:$1" "${@:2}"
33 |
34 | echo "erro: linha ${BASH_LINENO[-2]:--}: ${FUNCNAME[-2]:--}: ${1:-fatal}" 1>&2
35 | exit 1
36 | }
37 |
38 | # .FUNCTION error.fatalf ... -> [str]|[bool]
39 | function error.fatalf()
40 | {
41 | getopt.parse -1 "fmt:str:$1" "args:str:$2" ... "${@:3}"
42 |
43 | printf "erro: linha %d: %s: ${1:-fatal}" \
44 | "${BASH_LINENO[-2]:--}" \
45 | "${FUNCNAME[-2]:--}" \
46 | "${@:2}" 1>&2
47 |
48 | exit 1
49 | }
50 |
51 | # .FUNCTION error.error -> [str]|[bool]
52 | function error.error()
53 | {
54 | getopt.parse 1 "error:str:$1" "${@:2}"
55 |
56 | echo "${FUNCNAME[-2]:--}: ${1:-error}" 1>&2
57 | return 1
58 | }
59 |
60 | # .FUNCTION error.errorf ... -> [str]|[bool]
61 | function error.errorf()
62 | {
63 | getopt.parse -1 "fmt:str:$1" "args:str:$2" ... "${@:3}"
64 |
65 | printf "${FUNCNAME[-2]:--}: ${1:-error}" "${@:2}" 1>&2
66 | return 1
67 | }
68 |
69 | # .FUNCTION error.warn -> [str]|[bool]
70 | function error.warn()
71 | {
72 | getopt.parse 1 "error:str:$1" "${@:2}"
73 |
74 | echo -e "\e[0;31m${FUNCNAME[-2]:--}: ${1:-warn}\e[0;m" 1>&2
75 | return 1
76 | }
77 |
78 | # .FUNCTION error.warnf ... -> [str]|[bool]
79 | function error.warnf()
80 | {
81 | getopt.parse -1 "error:str:$1" "args:str:$2" ... "${@:3}"
82 |
83 | printf "\e[0;31m${FUNCNAME[-2]:--}: ${1:-warn}\e[0;m" "${@:2}" 1>&2
84 | return 1
85 | }
86 |
87 | # .TYPE error_t
88 | #
89 | # Implementa o objeto 'S' com os métodos:
90 | #
91 | # S.fatal
92 | # S.fatalf
93 | # S.error
94 | # S.errorf
95 | # S.warn
96 | # S.warnf
97 | #
98 | typedef error_t \
99 | error.fatal \
100 | error.fatalf \
101 | error.error \
102 | error.errorf \
103 | error.warn \
104 | error.warnf
105 |
106 | readonly -f error.fatal \
107 | error.fatalf \
108 | error.error \
109 | error.errorf \
110 | error.warn \
111 | error.warnf
112 |
113 | # /* __ERROR_SH__ */
114 |
--------------------------------------------------------------------------------
/src/grp.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Copyright 2018 Juliano Santos [SHAMAN]
4 | #
5 | # This file is part of bashsrc.
6 | #
7 | # bashsrc is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # bashsrc is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with bashsrc. If not, see .
19 |
20 | [ -v __GRP_SH__ ] && return 0
21 |
22 | readonly __GRP_SH__=1
23 |
24 | source builtin.sh
25 |
26 | # .FUNCTION grp.getgroups -> [uint]|[bool]
27 | #
28 | # Retorna os IDs de grupo suplementares da chamada do processo.
29 | #
30 | function grp.getgroups()
31 | {
32 | getopt.parse 0 "$@"
33 |
34 | printf '%s\n' ${GROUPS[@]}
35 | return $?
36 | }
37 |
38 | # .FUNCTION grp.getgrall -> [str]|[bool]
39 | #
40 | # Retorna uma lista com todos os grupos do sistema.
41 | #
42 | function grp.getgrall()
43 | {
44 | getopt.parse 0 "$@"
45 |
46 | local grp
47 |
48 | while IFS=':' read grp _; do
49 | echo $grp
50 | done < /etc/group
51 |
52 | return $?
53 | }
54 |
55 | # .FUNCTION grp.getgrnam -> [bool]
56 | #
57 | # Obtém no banco de dados as informações do grupo especificado.
58 | #
59 | function grp.getgrnam()
60 | {
61 | getopt.parse 2 "name:str:$1" "grp:map:$2" "${@:3}"
62 |
63 | local __name__ __pass__ __gid__ __mem__
64 | local -n __ref__=$2
65 |
66 | __ref__=() || return 1
67 |
68 | while IFS=':' read __name__ \
69 | __pass__ \
70 | __gid__ \
71 | __mem__; do
72 | [[ $1 == $__name__ ]] && break
73 | done < /etc/group
74 |
75 | (($?)) && { error.error "'$1' grupo não encontrado"; return $?; }
76 |
77 | __ref__[gr_name]=$__name__
78 | __ref__[gr_passwd]=$__pass__
79 | __ref__[gr_gid]=$__gid__
80 | __ref__[gr_mem]=$__mem__
81 |
82 | return $?
83 | }
84 |
85 | # .FUNCTION grp.getgrgid -> [bool]
86 | #
87 | # Obtém no banco de dados as informações do id do grupo especificado.
88 | #
89 | function grp.getgrgid()
90 | {
91 | getopt.parse 2 "gid:uint:$1" "grp:map:$2" "${@:3}"
92 |
93 | local __name__ __pass__ __gid__ __mem__
94 | local -n __ref__=$2
95 |
96 | __ref__=() || return 1
97 |
98 | while IFS=':' read __name__ \
99 | __pass__ \
100 | __gid__ \
101 | __mem__; do
102 | [[ $1 == $__gid__ ]] && break
103 | done < /etc/group
104 |
105 | (($?)) && { error.error "'$1' gid não encontrado"; return $?; }
106 |
107 | __ref__[gr_name]=$__name__
108 | __ref__[gr_passwd]=$__pass__
109 | __ref__[gr_gid]=$__gid__
110 | __ref__[gr_mem]=$__mem__
111 |
112 | return $?
113 | }
114 |
115 | # .MAP grp
116 | #
117 | # Chaves:
118 | #
119 | # gr_name /* Nome do grupo */
120 | # gr_passwd /* Senha criptgrafada do grupo ou vazio. */
121 | # gr_gid /* Identificador númerico do grupo */
122 | # gr_mem /* Lista de usuários ou membros do grupos separados por vírgula (,). */
123 | #
124 |
125 | # Funções (somente leitura)
126 | readonly -f grp.getgroups \
127 | grp.getgrall \
128 | grp.getgrnam \
129 | grp.getgrgid
130 |
131 | # /* __GRP_SH__ */
132 |
133 |
--------------------------------------------------------------------------------
/src/mem.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #
3 | # Copyright 2018 Juliano Santos [SHAMAN]
4 | #
5 | # This file is part of bashsrc.
6 | #
7 | # bashsrc is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # bashsrc is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with bashsrc. If not, see .
19 |
20 | [ -v __MEM_SH__ ] && return 0
21 |
22 | readonly __MEM_SH__=1
23 |
24 | source builtin.sh
25 |
26 | # .FUNCTION mem.stats -> [bool]
27 | #
28 | # Obtém estatisticas de uso da memória do sistema.
29 | #
30 | function mem.stats()
31 | {
32 | getopt.parse 1 "stats:map:$1" "${@:2}"
33 |
34 | local __flag__ __size__
35 | local -n __ref__=$1
36 |
37 | # Inicializa.
38 | __ref__=() || return 1
39 |
40 | while IFS=':' read __flag__ __size__; do
41 | IFS=' ' read __size__ _ <<< $__size__
42 | __ref__[${__flag__,,}]=$__size__
43 | done < /proc/meminfo
44 |
45 | return $?
46 | }
47 |
48 | # .FUNCTION mem.physical -> [bool]
49 | #
50 | # Obtém informações da memória física.
51 | #
52 | function mem.physical()
53 | {
54 | getopt.parse 1 "mem:map:$1" "${@:2}"
55 |
56 | local __flag__ __size__
57 | local -n __ref__=$1
58 |
59 | __ref__=() || return 1
60 |
61 | while IFS=':' read __flag__ __size__; do
62 | IFS=' ' read __size__ _ <<< $__size__
63 | __flag__=${__flag__,,}
64 | [[ $__flag__ == @(memtotal|memfree|memavailable|cached) ]] &&
65 | __ref__[$__flag__]=$__size__
66 | done < /proc/meminfo
67 |
68 | return $?
69 | }
70 |
71 | # .FUNCTION mem.swap -> [bool]
72 | #
73 | # Obtém informações da memória virtual.
74 | #
75 | function mem.swap()
76 | {
77 | getopt.parse 1 "swap:map:$1" "${@:2}"
78 |
79 | local __flag__ __size__
80 | local -n __ref__=$1
81 |
82 | __ref__=() || return 1
83 |
84 | while IFS=':' read __flag__ __size__; do
85 | IFS=' ' read __size__ _ <<< $__size__
86 | __flag__=${__flag__,,}
87 | [[ $__flag__ == @(swaptotal|swapcached|swapfree) ]] &&
88 | __ref__[$__flag__]=$__size__
89 | done < /proc/meminfo
90 |
91 | return $?
92 | }
93 |
94 | # .MAP stats
95 | #
96 | # Chaves:
97 | #
98 | # directmap4k
99 | # hugepages_total
100 | # vmalloctotal
101 | # anonhugepages
102 | # shmemhugepages
103 | # bounce
104 | # active(file)
105 | # buffers
106 | # inactive(file)
107 | # active
108 | # sunreclaim
109 | # inactive(anon)
110 | # mapped
111 | # swaptotal
112 | # swapcached
113 | # hardwarecorrupted
114 | # commitlimit
115 | # memfree
116 | # slab
117 | # writeback
118 | # nfs_unstable
119 | # inactive
120 | # cached
121 | # hugepagesize
122 | # shmem
123 | # dirty
124 | # hugepages_free
125 | # memavailable
126 | # cmatotal
127 | # kernelstack
128 | # cmafree
129 | # sreclaimable
130 | # unevictable
131 | # shmempmdmapped
132 | # writebacktmp
133 | # memtotal
134 | # hugepages_rsvd
135 | # vmallocused
136 | # directmap2m
137 | # swapfree
138 | # active(anon)
139 | # vmallocchunk
140 | # committed_as
141 | # anonpages
142 | # mlocked
143 | # hugepages_surp
144 | # pagetables
145 | #
146 |
147 | # .MAP meminfo
148 | #
149 | # Chaves:
150 | #
151 | # memfree
152 | # cached
153 | # memavailable
154 | # memtotal
155 | #
156 |
157 | # .MAP swap
158 | #
159 | # Chaves:
160 | #
161 | # swaptotal
162 | # swapcached
163 | # swapfree
164 | #
165 |
166 | # Funções
167 | readonly -f mem.stats \
168 | mem.physical \
169 | mem.swap
170 |
171 | # /* __MEM_SH__ */
172 |
--------------------------------------------------------------------------------
/src/json.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Copyright 2018 Juliano Santos [SHAMAN]
4 | #
5 | # This file is part of bashsrc.
6 | #
7 | # bashsrc is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # bashsrc is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with bashsrc. If not, see .
19 |
20 | [ -v __JSON_SH__ ] && return 0
21 |
22 | readonly __JSON_SH__=1
23 |
24 | source builtin.sh
25 | source setup.sh
26 |
27 | # Dependência.
28 | setup.package 'jq (>= 1.5)'
29 |
30 | # .FUNCTION json.load -> [bool]
31 | #
32 | # Converte o arquivo contendo um documento JSON em uma estrutura
33 | # de dados mapeada e salva no objeto apontado por 'obj'.
34 | #
35 | function json.load()
36 | {
37 | getopt.parse 2 "file:str:$1" "obj:map:$2" "${@:3}"
38 |
39 | if [ ! -f "$1" ]; then
40 | error.error "'$1' não é um arquivo regular"
41 | return $?
42 | elif [ ! -r "$1" ]; then
43 | error.error "'$1' não foi possível ler o arquivo"
44 | return $?
45 | fi
46 |
47 | json.__setmap__ file "$1" $2
48 |
49 | return $?
50 | }
51 |
52 | # .FUNCTION json.loads -> [bool]
53 | #
54 | # Converte a expressão JSON em uma estrutura de dados mapeada
55 | # e salva no objeto apontado por 'obj'.
56 | #
57 | # == EXEMPLO ==
58 | #
59 | # #!/bin/bash
60 | #
61 | # source json.sh
62 | # source map.sh
63 | #
64 | # # Inicializa o map.
65 | # declare -A dados=()
66 | #
67 | # # Implementa o tipo map.
68 | # var dados map_t
69 | #
70 | # # Processando/convertendo JSON
71 | # json.loads '{"autor":{"nome":"Juliano","sobrenome":"santos","idade":35,"pseudonimo":"SHAMAN"}}' dados
72 | #
73 | # Listando as chaves do mapa.
74 | # dados.keys
75 | #
76 | # echo ---
77 | #
78 | # # Acessando valores.
79 | # dados.get autor.nome
80 | # dados.get autor.pseudonimo
81 | # dados.get autor.idade
82 | #
83 | # == SAÍDA ==
84 | #
85 | # autor.nome
86 | # autor.pseudonimo
87 | # autor.sobrenome
88 | # autor.idade
89 | # ---
90 | # Juliano
91 | # SHAMAN
92 | # 35
93 | #
94 | function json.loads()
95 | {
96 | getopt.parse 2 "expr:str:$1" "obj:map:$2" "${@:3}"
97 | json.__setmap__ expr "$1" $2
98 | return $?
99 | }
100 |
101 | # json.__setmap____