-
Notifications
You must be signed in to change notification settings - Fork 9
/
shell-var
91 lines (83 loc) · 1.99 KB
/
shell-var
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
#!/bin/sh -efu
### This file is covered by the GNU General Public License,
### which should be included with libshell as the file LICENSE.
### All copyright information are listed in the COPYING.
if [ -z "${__included_shell_var-}" ]; then
__included_shell_var=1
. shell-error
shell_var_is_number()
{
[ -n "${1##0*}" ] && [ -n "${1##*[!0-9]*}" ] && [ "$1" -gt 0 ] 2>/dev/null ||
return 1
}
shell_var_is_yes()
{
[ "$#" -eq 1 ] ||
fatal "Usage: shell_var_yes value"
case "$1" in
[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|[Yy]|1) return 0 ;;
esac
return 1
}
shell_var_is_no()
{
[ "$#" -eq 1 ] ||
fatal "Usage: shell_var_no value"
case "$1" in
[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|[Nn]|0) return 0 ;;
esac
return 1
}
### Strip whitespace from the beginning and end of a string
### Usage: shell_var_trim retval " aaa bb aaa "; echo "[$retval]"
### [aaa bb aaa]
shell_var_trim()
{
[ "$#" -eq 2 ] ||
fatal "Usage: shell_var_trim varname value"
__shell_var_trim()
{
unset -f __shell_var_trim
local r="$1" space='
'
while [ -n "$r" ] && [ -z "${r##[$space]*[$space]}" ]; do r="${r%?}"; r="${r#?}"; done
while [ -n "$r" ] && [ -z "${r##*[$space]}" ]; do r="${r%?}"; done
while [ -n "$r" ] && [ -z "${r%%[$space]*}" ]; do r="${r#?}"; done
__shell_var_trimo="$r"
}
local __shell_var_trimo=
__shell_var_trim "$2"
eval "$1=\"\$__shell_var_trimo\""
}
### Remove quote symbol from string
### Usage example:
### for i in "\"str1\"" "'str2'" "\"str3'"; do
### shell_var_unquote var "$i";
### echo "$var";
### done
###
### Result:
### str1
### str2
### "str3'
###
shell_var_unquote()
{
[ "$#" -eq 2 ] ||
fatal "Usage: shell_var_unquote varname value"
__shell_var_unquote()
{
local o="$1"
if [ -z "${o##*\'}${o%%\'*}" ]; then
o="${o#\'}" o="${o%\'}"
elif [ -z "${o##*\"}${o%%\"*}" ]; then
o="${o#\"}" o="${o%\"}"
fi
__shell_var_unquoteo="$o"
}
local __shell_var_unquoteo
__shell_var_unquote "$2"
unset -f __shell_var_unquote
eval "$1=\"\$__shell_var_unquoteo\""
}
fi #__included_shell_var