0%

【Shell】标准的 Shell 脚本

记录一下 shell 脚本模板。

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
#!/usr/bin/env bash

args_num=$#
action="${1}"

ALLOWED_ACTION_ARGS=("set" "unset" "test")


function print_ok() {
local msg="${1}"
echo "${msg}"
}

function print_err() {
local msg="${1}"
echo "${msg}" > /dev/stderr
}

function contain() {
local list="${1}"
local ele="${2}"
for i in ${list[*]};
do
if [ "${ele}" == "${i}" ]; then
return 0
fi
done
return 1
}

function check_args_num() {
if [ ${args_num} != 1 ]; then
print_err "Wrong args num"
return 1
fi
}

function check_action_arg() {
if ! contain "${ALLOWED_ACTION_ARGS[*]}" "${action}"; then
print_err "Action arg must be [ set || unset || test ]"
return 1
fi
}

function set_proxy () {
export ALL_PROXY=http://www.vksir.zone
print_ok "Set proxy success"
}

function unset_proxy() {
unset ALL_PROXY
print_ok "Unset proxy success"
}

function test_proxy() {
if curl -k https://www.google.com --connect-timeout 3 >/dev/null 2>&1; then
print_ok "Proxy is available"
else
print_err "Proxy is not available"
fi
}


if ! check_args_num; then
return 1
fi
if ! check_action_arg; then
return 1
fi

if [ "${action}" == "set" ]; then
set_proxy
elif [ "${action}" == "unset" ]; then
unset_proxy
elif [ "${action}" == "test" ]; then
test_proxy
fi

return $?
1
2
3
source proxy set
source proxy unset
source proxy test

注意,这里如果想写 source 脚本,那就不能使用 exit,否则会使 ssh 会话退出。