-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbash_header.tpl
executable file
·432 lines (376 loc) · 11.5 KB
/
bash_header.tpl
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
#!/usr/bin/env bash
# Sources: http://www.gmarik.info/blog/2016/5-tips-for-solid-bash-code/
# https://natelandau.com/boilerplate-shell-script-template/
# https://github.com/natelandau/shell-scripts
#
# Script-Name : myscriptz.sh
# Version : 0.0.1
# Autor : Tobias Kern
# Datum : $(date)
# Lizenz : GPLv3
# Depends :
# Use :
#
# Example:
#
# Description:
#
###########################################################################################
################# Default Functions ################
###########################################################################################
#
# readFile
# ------------------------------------------------------
# Function to read a line from a file.
#
# Most often used to read the config files saved in my etc directory.
# Outputs each line in a variable named $result
# ------------------------------------------------------
function readFile() {
unset "${result}"
while read result
do
echo "${result}"
done < "$1"
}
# needSudo
# ------------------------------------------------------
# If a script needs sudo access, call this function which
# requests sudo access and then keeps it alive.
# ------------------------------------------------------
function needSudo() {
# Update existing sudo time stamp if set, otherwise do nothing.
sudo -v
while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null &
}
# Print Date
print_date() {
echo "today is $(date)"
}
# File Checks
# ------------------------------------------------------
# A series of functions which make checks against the filesystem. For
# use in if/then statements.
#
# Usage:
# if is_file "file"; then
# ...
# fi
# ------------------------------------------------------
function is_exists() {
if [[ -e "$1" ]]; then
return 0
fi
return 1
}
function is_not_exists() {
if [[ ! -e "$1" ]]; then
return 0
fi
return 1
}
function is_file() {
if [[ -f "$1" ]]; then
return 0
fi
return 1
}
function is_not_file() {
if [[ ! -f "$1" ]]; then
return 0
fi
return 1
}
function is_dir() {
if [[ -d "$1" ]]; then
return 0
fi
return 1
}
function is_not_dir() {
if [[ ! -d "$1" ]]; then
return 0
fi
return 1
}
function is_symlink() {
if [[ -L "$1" ]]; then
return 0
fi
return 1
}
function is_not_symlink() {
if [[ ! -L "$1" ]]; then
return 0
fi
return 1
}
function is_empty() {
if [[ -z "$1" ]]; then
return 0
fi
return 1
}
function is_not_empty() {
if [[ -n "$1" ]]; then
return 0
fi
return 1
}
# set productiv environment
env_prod() {
local NAME=${NAME?"Required"}
# sets fail early flag
set -e
}
# set test environment
env_test() {
# enable debugging output
set -x
}
# Test which OS the user runs
# $1 = OS to test
# Usage: if is_os 'darwin'; then
function is_os() {
if [[ "${OSTYPE}" == $1* ]]; then
return 0
fi
return 1
}
# Text Transformations
# -----------------------------------
# Transform text using these functions.
# Adapted from https://github.com/jmcantrell/bashful
# -----------------------------------
lower() {
# Convert stdin to lowercase.
# usage: text=$(lower <<<"$1")
# echo "MAKETHISLOWERCASE" | lower
tr '[:upper:]' '[:lower:]'
}
upper() {
# Convert stdin to uppercase.
# usage: text=$(upper <<<"$1")
# echo "MAKETHISUPPERCASE" | upper
tr '[:lower:]' '[:upper:]'
}
ltrim() {
# Removes all leading whitespace (from the left).
local char=${1:-[:space:]}
sed "s%^[${char//%/\\%}]*%%"
}
rtrim() {
# Removes all trailing whitespace (from the right).
local char=${1:-[:space:]}
sed "s%[${char//%/\\%}]*$%%"
}
trim() {
# Removes all leading/trailing whitespace
# Usage examples:
# echo " foo bar baz " | trim #==> "foo bar baz"
ltrim "$1" | rtrim "$1"
}
squeeze() {
# Removes leading/trailing whitespace and condenses all other consecutive
# whitespace into a single space.
#
# Usage examples:
# echo " foo bar baz " | squeeze #==> "foo bar baz"
local char=${1:-[[:space:]]}
sed "s%\(${char//%/\\%}\)\+%\1%g" | trim "$char"
}
squeeze_lines() {
# <doc:squeeze_lines> {{{
#
# Removes all leading/trailing blank lines and condenses all other
# consecutive blank lines into a single blank line.
#
# </doc:squeeze_lines> }}}
sed '/^[[:space:]]\+$/s/.*//g' | cat -s | trim_lines
}
progressBar() {
# progressBar
# -----------------------------------
# Prints a progress bar within a for/while loop.
# To use this function you must pass the total number of
# times the loop will run to the function.
#
# usage:
# for number in $(seq 0 100); do
# sleep 1
# progressBar 100
# done
# -----------------------------------
if [[ "${quiet}" = "true" ]] || [ "${quiet}" == "1" ]; then
return
fi
local width
width=30
bar_char="#"
# Don't run this function when scripts are running in verbose mode
if ${verbose}; then return; fi
# Reset the count
if [ -z "${progressBarProgress}" ]; then
progressBarProgress=0
fi
# Do nothing if the output is not a terminal
if [ ! -t 1 ]; then
echo "Output is not a terminal" 1>&2
return
fi
# Hide the cursor
tput civis
trap 'tput cnorm; exit 1' SIGINT
if [ ! "${progressBarProgress}" -eq $(( $1 - 1 )) ]; then
# Compute the percentage.
perc=$(( progressBarProgress * 100 / $1 ))
# Compute the number of blocks to represent the percentage.
num=$(( progressBarProgress * width / $1 ))
# Create the progress bar string.
bar=
if [ ${num} -gt 0 ]; then
bar=$(printf "%0.s${bar_char}" $(seq 1 ${num}))
fi
# Print the progress bar.
progressBarLine=$(printf "%s [%-${width}s] (%d%%)" "Running Process" "${bar}" "${perc}")
echo -en "${progressBarLine}\r"
progressBarProgress=$(( progressBarProgress + 1 ))
else
# Clear the progress bar when complete
echo -ne "${width}%\033[0K\r"
unset progressBarProgress
fi
tput cnorm
}
################################################################################################
############ ERROR Codes ###################
################################################################################################
# Name of your script.
SCRIPTNAME=$(basename $0.sh)
# exit code without any error
EXIT_SUCCESS=0
# exit code I/O failure
EXIT_FAILURE=1
# exit code error if known
EXIT_ERROR=2
# unknown ERROR
EXIT_BUG=10
#################################################################################################
########## working with getopts #################
#################################################################################################
file= verbose= quiet= long=
while getopts :f:vql opt
do
case $opt in
f) file=$OPTARG
;;
v) verbose=true
quit=
;;
q) quiet=true
verbose=
;;
l) long=true
;;
'?') echo $0: $1: unrecognized option -$OPTARG >&2
echo "Usage: $0 [-f file] [-vql] [files ...]" >&2
exit 1
;;
esac
done
######################################################################################################
############## Bash environment variables ####################
######################################################################################################
# Posision from function to script
POSTOFONCA="*"
# Posision from function to script
POSTOFONCONCE="@"
# Options by execute bash
BACHEXECOP="-"
# Exit state from last command
STATELASTCOMMAND="?"
# Variable for optionsswitch
#OPTFILE=""
fbname=$(basename "$1".txt)
# SCRIPTNAME
# ------------------------------------------------------
# Will return the name of the script being run
# ------------------------------------------------------
scriptName=`basename $0` #Set Script Name variable
scriptBasename="$(basename ${scriptName} .sh)" # Strips '.sh' from scriptName
# TIMESTAMPS
# ------------------------------------------------------
# Prints the current date and time in a variety of formats:
#
# ------------------------------------------------------
now=$(LC_ALL=C date +"%m-%d-%Y %r") # Returns: 06-14-2015 10:34:40 PM
datestamp=$(LC_ALL=C date +%Y-%m-%d) # Returns: 2015-06-14
hourstamp=$(LC_ALL=C date +%r) # Returns: 10:34:40 PM
timestamp=$(LC_ALL=C date +%Y%m%d_%H%M%S) # Returns: 20150614_223440
today=$(LC_ALL=C date +"%m-%d-%Y") # Returns: 06-14-2015
longdate=$(LC_ALL=C date +"%a, %d %b %Y %H:%M:%S %z") # Returns: Sun, 10 Jan 2016 20:47:53 -0500
gmtdate=$(LC_ALL=C date -u -R | sed 's/\+0000/GMT/') # Returns: Wed, 13 Jan 2016 15:55:29 GMT
# THISHOST
# ------------------------------------------------------
# Will print the current hostname of the computer the script
# is being run on.
# ------------------------------------------------------
thisHost=$(hostname)
parse_yaml() {
# Function to parse YAML files and add values to variables. Send it to a temp file and source it
# https://gist.github.com/DinoChiesa/3e3c3866b51290f31243 which is derived from
# https://gist.github.com/epiloque/8cf512c6d64641bde388
#
# Usage:
# $ parse_yaml sample.yml > /some/tempfile
#
# parse_yaml accepts a prefix argument so that imported settings all have a common prefix
# (which will reduce the risk of name-space collisions).
#
# $ parse_yaml sample.yml "CONF_"
local prefix=$2
local s
local w
local fs
s='[[:space:]]*'
w='[a-zA-Z0-9_]*'
fs="$(echo @|tr @ '\034')"
sed -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
-e "s|^\($s\)\($w\)$s[:-]$s\(.*\)$s\$|\1$fs\2$fs\3|p" "$1" |
awk -F"$fs" '{
indent = length($1)/2;
if (length($2) == 0) { conj[indent]="+";} else {conj[indent]="";}
vname[indent] = $2;
for (i in vname) {if (i > indent) {delete vname[i]}}
if (length($3) > 0) {
vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
printf("%s%s%s%s=(\"%s\")\n", "'"$prefix"'",vn, $2, conj[indent-1],$3);
}
}' | sed 's/_=/+=/g'
}
function json2yaml() {
# convert json files to yaml using python and PyYAML
python -c 'import sys, yaml, json; yaml.safe_dump(json.load(sys.stdin), sys.stdout, default_flow_style=False)' < "$1"
}
function yaml2json() {
# convert yaml files to json using python and PyYAML
python -c 'import sys, yaml, json; json.dump(yaml.load(sys.stdin), sys.stdout, indent=4)' < "$1"
}
###########################################################################################################
########### Colors in shell ######################
###########################################################################################################
black() { echo "$(tput setaf 0)$*$(tput setaf 9)"; }
red() { echo "$(tput setaf 1)$*$(tput setaf 9)"; }
green() { echo "$(tput setaf 2)$*$(tput setaf 9)"; }
yellow() { echo "$(tput setaf 3)$*$(tput setaf 9)"; }
blue() { echo "$(tput setaf 4)$*$(tput setaf 9)"; }
magenta() { echo "$(tput setaf 5)$*$(tput setaf 9)"; }
cyan() { echo "$(tput setaf 6)$*$(tput setaf 9)"; }
white() { echo "$(tput setaf 7)$*$(tput setaf 9)"; }
###########################################################################################################
########## MyScript #############################
###########################################################################################################
main() {
print_date
env_prod
}