-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbash_utils
More file actions
130 lines (115 loc) · 2.18 KB
/
bash_utils
File metadata and controls
130 lines (115 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#!/usr/bin/env bash
# if [[ -s "${HOME}/.bash_utils" ]]; then
# source "${HOME}/.bash_utils"
# elif [[ -s "${HOME}/dotfiles/.bash_utils" ]]; then
# source "${HOME}/dotfiles/.bash_utils"
# else
# printf '\e[31m~/cannot source bash_utils \e[0m\n' >&2
# fi
declare -A colors
colors[reset]=$(tput sgr0)
colors[black]=$(tput setaf 0)
colors[red]=$(tput setaf 1)
colors[green]=$(tput setaf 2)
colors[yellow]=$(tput setaf 3)
colors[blue]=$(tput setaf 4)
colors[magenta]=$(tput setaf 5)
colors[cyan]=$(tput setaf 6)
colors[grey]=$(tput setaf 7)
colors[lblack]=$(tput setaf 8)
colors[lred]=$(tput setaf 9)
colors[lgreen]=$(tput setaf 10)
colors[lyellow]=$(tput setaf 11)
colors[lblue]=$(tput setaf 12)
colors[lmagenta]=$(tput setaf 13)
colors[lcyan]=$(tput setaf 14)
colors[lgrey]=$(tput setaf 15)
color() {
local c
c="$1"
shift
printf '%s' "${colors[$c]}"
printf '%s\n' "$@"
printf '%s' "${colors[reset]}"
}
in_term() {
[[ -t 0 && -t 1 ]]
}
is_running() {
pgrep "$1" &> /dev/null
}
info() {
color green "$@" >&2
}
color() {
local c
c="$1"
shift
printf '%s' "${colors[$c]}"
printf '%s\n' "$@"
printf '%s' "${colors[reset]}"
}
err() {
color red "$@" >&2
}
die() {
[[ -n "$1" ]] && err "$1"
exit 1
}
has() {
local o c loud
loud=0
while getopts 'v' o; do
case "$o" in
v) loud=1 ;;
esac
done
shift "$((OPTIND-1))"
for c; do c="${c%% *}"
if ! command -v "$c" &> /dev/null; then
(( loud )) && err "$c not found"
return 1
fi
done
}
select_from() {
local a c cmd
cmd='command -v'
[[ -n $ZSH_VERSION ]] && emulate -L bash
for a in "$@"; do
case "$a" in
-c) cmd="$2"; shift 2 ;;
esac
done
for c in "$@"; do
if $cmd "${c%% *}" &> /dev/null; then
echo "$c"
return 0
fi
done
return 1
}
ask() {
read -r -n1 -p "$* " ans
printf '\n'
[[ ${ans^} = Y* ]]
}
prompt() {
local opts=() one
for a; do
case "$a" in
-1) opts+=( '-n1' ); one=1; shift ;;
-s) opts+=( '-s' ); shift ;;
esac
done
read -e -r "${opts[@]}" -p "$* " ans
if [[ $one = 1 ]]; then
printf '\n'
if [[ ${ans,} = y ]]; then
return 0
else
return 1
fi
fi
printf '%s\n' "$ans"
}