-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
db
executable file
·76 lines (61 loc) · 1.58 KB
/
db
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
#!/usr/bin/env bash
usage()
{
printf "%b" "
Usage:
db database_file {{key}} {{value}} # set
db database_file {{key}} # get
db database_file {{key}} unset # unset
" >&2
}
if [[ -f "$1" ]]
then
database_file="$1"
shift
if [[ ! -f "$database_file" ]]
then
directory=$(dirname "$database_file")
[[ -d "$directory" ]] || mkdir -p "$directory"
touch "$database_file"
fi
else
printf "%b" "\n\nDatabase file $1 does not exist.\n\n" >&2
exit 1
fi
key="$1"
shift
if [[ -z "$key" ]]
then
usage
exit 1
else
if (( ${escape_flag:-0} ))
then
escaped_key="$(\printf "%b" "$key" | \sed -e 's#\\#\\#g' -e 's#/#\\/#g' -e 's#\.#\.#g')"
else
escaped_key="$key"
fi
value="$*"
if [[ "unset" == "$value" || "delete" == "$value" ]]
then
\sed -e "s#^$escaped_key=.*\$##" -e '/^$/d' "$database_file" \
> "$database_file.new"
mv "$database_file.new" "$database_file"
else
if [[ -z "$value" ]]
then # get
[[ -s "${database_file}" ]] || exit 0 # File is empty, nothing to get.
\awk -F= '/^'"$escaped_key"'=/' "$database_file" \
| \sed -e "s#^$escaped_key=##" -e '/^$/d'
else # set
\sed -e "s#^$escaped_key=.*\$##" -e '/^$/d' "$database_file" > "$database_file.new"
mv "$database_file.new" "$database_file"
if [[ -z "$(awk -F= "/^'"$escaped_key"'=/{print $2}" "$database_file")" ]]
then # append
echo "$escaped_key=$value" >> "$database_file"
else # overwrite
__rvm_sed_i "$dtabase_file" -e "s#^$escaped_key=.*\$#$escaped_key=$value#"
fi
fi
fi
fi