/
shellfunc
3945 lines (3574 loc) · 77.4 KB
/
shellfunc
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, June 1991.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/gpl-2.0.html>
# Copyright 2006-2016 - Cathedral Networks <admin@cathedral-networks.org>
# Description:
#
# Somewhat useful shell functions, mostly developed for internal use
#
# Please note: Some of these are likely broken, or written to suit a very
# specialized scenario. Please read each function carefully
# before use, to ensure you know what it does
#
# include guard (..ish)
if [[ -z "${_sf_loaded:-}" ]]; then
_sf_loaded=true
else
return 0
fi
# needed for runfunc to find the functions
_shellfunc_header="sf_"
# safe printing
function sf_print { builtin printf '%s' "$*"; }
function sf_println { builtin printf '%s\n' "$*"; }
# print to stdout
function sf_stdout { { echo -e "$@"; } 2>/dev/null; }
function sf_stdoutv { ! ${_sf_verbose:-true} || sf_stdout "$@"; }
function sf_stdouti { ! sf_terminal || sf_stdout "$@"; }
# print usage
function sf_usage { sf_stderr "Usage: $*"; }
# output information, warnings and errors to stderr
function sf_stderr { echo -e "$@" >&2; }
function sf_stderrv { ! ${_sf_verbose:-true} || sf_stderr "$@"; }
function sf_stderri { ! sf_terminal || sf_stderr "$@"; }
function sf_info { printf "Info: " >&2 && sf_stderr "$@"; }
function sf_infov { ! ${_sf_verbose:-true} || sf_info "$@"; }
function sf_infoi { ! sf_terminal || sf_info "$@"; }
function sf_warning { printf "Warning: " >&2 && sf_stderr "$@"; }
function sf_warningv { ! ${_sf_verbose:-true} || sf_warning "$@"; }
function sf_warningi { ! sf_terminal || sf_warning "$@"; }
function sf_error { printf "Error: " >&2 && sf_stderr "$@"; }
function sf_errorv { ! ${_sf_verbose:-true} || sf_error "$@"; }
function sf_errori { ! sf_terminal || sf_error "$@"; }
# error messages
function sf_error_unknown_option { sf_error "Unknown option -${OPTARG}"; }
function sf_warning_unknown_option { sf_warning "Unknown option -${OPTARG}"; }
function sf_error_missing_argument { sf_error "Option -${OPTARG} requires an argument"; }
function sf_error_tput { sf_error "tput does not function correctly on your terminal!"; }
# print a message within an 80 character wide line
function sf_line80
{
local stderr=false prenewline=false postnewline=false parens=true symbol="="
local OPTIND=1 OPTARG OPTERR opt
while getopts ":ehnNs" opt; do
case "$opt" in
e) stderr=true ;;
s) symbol="-" ;;
h) symbol="#"; parens=false ;;
n) prenewline=true ;;
N) postnewline=true ;;
[?])
sf_error_unknown_option
return 1
;;
:)
sf_error_missing_argument
return 1
;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
if (( $# > 2 )); then
sf_usage "$FUNCNAME <string> [length (int)]"
return 1
fi
local string
read -r string <<<"${1:-}"
if [[ -n "$string" ]]; then
string=" ${string} "
if $parens; then
string="(${string})"
fi
fi
if [[ -n "${2:-}" ]]; then
sf_integer -vq "$2" || return $?
local width=$(( $2 > 0 ? $2 + $((parens ? 4 : 2)) : 0 ))
else
local width=${#string}
fi
if (( width > 78 )); then
sf_warning "Text too long for $FUNCNAME: $1"
return 1
fi
local right=$(( 40 - width / 2 ))
local left=$(( right - width % 2 ))
left=$(printf "%${left}s" "")
right=$(printf "%${right}s" "")
if $stderr; then
! $prenewline || sf_stderr
sf_stderr "${left// /$symbol}${string}${right// /$symbol}"
! $postnewline || sf_stderr
else
! $prenewline || sf_stdout
sf_stdout "${left// /$symbol}${string}${right// /$symbol}"
! $postnewline || sf_stdout
fi
}
# copy a function (will not overwrite existing ones)
function sf_fcopy
{
if (( $# != 2 )); then
sf_usage "$FUNCNAME <source> <destination>"
return 1
fi
if ! declare -f "$1" >/dev/null; then
sf_error "$FUNCNAME: source function $1 is not defined!"
return 1
fi
if declare -f "$2" >/dev/null; then
return 1
fi
eval "$(declare -f "$1" | sed "0,/${1}/{s/${1}/${2}/}")"
}
# get unix time
function sf_unixtime { date "$@" +'%s'; }
# get a standard cathedral timestamp
function sf_timestamp { date "$@" +'%Y-%m-%d %H:%M:%S %z'; }
function sf_timestampZ { date "$@" +'%Y-%m-%d %H:%M:%S %Z'; }
function sf_timestamp_short { date "$@" +'%Y-%m-%d %H:%M:%S'; }
# get a military style date
function sf_date { date "$@" +'%Y%m%d'; }
# get a timestamp for backup filenames
function sf_timestamp_backup { date "$@" +"%Y%m%dT%H%M%S"; }
# check if we're online
function sf_online
{(
local ipopt='--prefer-family=IPv4'
local OPTIND=1 OPTARG OPTERR opt
while getopts ":46" opt; do
case "$opt" in
4) ipopt="--inet4-only" ;;
6) ipopt="--inet6-only" ;;
[?])
sf_error_unknown_option
return 1
;;
:)
sf_error_missing_argument
return 1
;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
function check
{
if sf_timeout 30 wget $ipopt --spider --timeout=28 --tries=1 "$@" >/dev/null 2>&1; then
return 0
fi
sleep 1
return 1
}
if
check google.com || check microsoft.com || check debian.org || check kernel.org
then
return 0
else
return 1
fi
)}
# get the size of a file in bytes
function sf_size
{
if (( $# != 1 )); then
sf_usage "$FUNCNAME <file>"
return 1
fi
if ! [[ -e "$1" ]]; then
sf_error "\"${1}\" does not exist!"
return 1
fi
stat --printf "%s" "$1"
}
# get the access-time on a file in seconds since epoch
function sf_atime
{
if (( $# != 1 )); then
sf_usage "$FUNCNAME <file>"
return 1
fi
if ! [[ -e "$1" ]]; then
sf_error "\"${1}\" does not exist!"
return 1
fi
case "$(sf_sysver)" in
*Debian*|*Ubuntu*|*BackTrack*|*Kali*|*Raspbian*)
stat -c '%X' "$1"
;;
FreeBSD*)
stat -f '%a' "$1"
;;
*)
sf_error "No idea how to get mtime on: $(sf_sysver)"
;;
esac
}
# get the modify-time on a file in seconds since epoch
function sf_mtime
{
if (( $# != 1 )); then
sf_usage "$FUNCNAME <file>"
return 1
fi
if ! [[ -e "$1" ]]; then
sf_error "\"${1}\" does not exist!"
return 1
fi
case "$(sf_sysver)" in
*Debian*|*Ubuntu*|*BackTrack*|*Kali*|*Raspbian*)
stat -c '%Y' "$1"
;;
FreeBSD*)
stat -f '%m' "$1"
;;
*)
sf_error "No idea how to get mtime on: $(sf_sysver)"
;;
esac
}
# support for old sudo versions in scripts
function sf_sudo
{
if sudo -nl >/dev/null 2>&1 <<<""; then
if sudo -n true 2>/dev/null; then
sudo -n "$@"
else
sf_warning "This script requires root permissions."
return 1
fi
else
sf_warning "Outdated sudo version without -n switch - the script may get stuck here"
sudo "$@"
fi
}
# get files and permissions recursively
function sf_permsave
{
if (( $# < 1 )); then
sf_usage "$FUNCNAME <dir> [dir] ..."
return 1
fi
while [[ -n "${1:-}" ]]; do
find "$1" -printf '%u\0%U\0%g\0%G\0%m\0%p\0%l\0'
shift
done
}
# set permissions recursively from a file
function sf_permload
{
local numeric=false
local dryrun=false
local skip=false
local user uid group gid perms file target
local OPTIND=1 OPTARG OPTERR opt
while getopts ":dns" opt; do
case "$opt" in
d) dryrun=true ;;
n) numeric=true ;;
s) skip=true ;;
[?])
sf_error_unknown_option
return 1
;;
:)
sf_error_missing_argument
return 1
;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
if (( $# < 1 )); then
sf_usage "$FUNCNAME <file> [file] ..."
return 1
fi
if ! $dryrun; then
sf_stderr
sf_stderr "This will read the provided files and overwrite permissions on the files described inside!"
fi
if $dryrun || sf_question -N "Are you sure you want to do this?"; then
while [[ -n "${1:-}" ]]; do
if ! sf_goodfile -v "$1" >/dev/null; then
return 1
fi
while
for i in user uid group gid perms file target; do
IFS= read -r -d $'\0' "$i"
done
do
! $skip || [[ -e "$file" ]] || continue
echo "${user}(${uid}) - ${group}(${gid}) - ${perms} - ${file}${target:+ => $target}"
if ! $dryrun; then
if [[ -n "$target" ]]; then
rm -rf "$file" 2>/dev/null || :
ln -sf "$target" "$file"
else
$numeric && chown "${uid}:${gid}" "$file" || chown "${user}:${group}" "$file"
chmod "$perms" "$file"
fi
fi
done <"$1"
shift
done
fi
}
# get the delta modify-time on a file in seconds from now (positive values for negative time, -60 is one minute in the future)
function sf_dmtime
{
if (( $# != 1 )); then
sf_usage "$FUNCNAME <file>"
return 1
fi
local mtime unixtime
mtime=$(sf_mtime "$1") || return 1
unixtime=$(sf_unixtime)
echo $((unixtime-mtime))
}
# trim whitespace
function sf_trim
{
{
if ! (( $# )); then
cat
else
echo "$@"
fi
} | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
}
# count down
function sf_countdown
{
if (( $# < 1 )) || (( $# > 2 )); then
sf_usage "$FUNCNAME [string] <integer>"
return 1
fi
local string=""
if (( $# == 2 )); then
string=$1
read -r string <<<"$string"
shift
fi
if ! sf_integer -vq -- "$1"; then
return 1
fi
if [[ -n "$string" ]]; then
echo -n "$string "
fi
local i
for(( i=$1; i>0; i-- )); do
echo -n "${i}.. "
sleep 1 || return $?
done
echo "0!"
}
# is X in the path?
function sf_inpath
{
if (( $# != 1 )); then
sf_usage "$FUNCNAME <path>"
return 1
fi
[[ ":${PATH}:" = *":${1}:"* ]]
}
# diff two files, print differences and replace
function sf_diffreplace
{
local replace=true
local create=false
local silent=false
local OPTIND=1 OPTARG OPTERR opt
while getopts ":ncs" opt; do
case "$opt" in
c) create=true ;;
n) replace=false ;;
s) silent=true ;;
[?])
sf_error_unknown_option
return 1
;;
:)
sf_error_missing_argument
return 1
;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
if (( $# < 2 )) || (( $# > 3 )); then
sf_usage "$FUNCNAME [-n] <oldfile> <newfile> [description]"
return 1
fi
local old=$1
local new=$2
local desc=${3:-${old}}
if ! sf_goodfile "$old" && $create && ! sf_mkfile -f "$old" >/dev/null; then
sf_error "Failed to create file \"$old\"!!"
return 1
fi
if ! sf_goodfile -wv "$old" >/dev/null || ! sf_goodfile "$new" >/dev/null; then
return 1
fi
$silent || sf_stdout "\nComparing..."
if ! diff -q "$old" "$new" &>/dev/null; then
if ! $silent; then
sf_stderr "Detected a change in \"${desc}\":"
diff "$old" "$new" >&2 || :
sf_stderr
fi
if $replace; then
$silent || sf_stderr "Installing new version of \"${desc}\"\n"
cat "$new" >"$old"
fi
return 0 # file was, or should be, replaced
else
$silent || sf_stdout "No change\n"
return 1
fi
}
# recursively kill processes
function sf_killtree
{
local pids ppid=$1 sig=${2:-"TERM"}
if ! kill -0 "$ppid"; then
builtin echo "killtree: ($ppid) - No such process" >&2
return 1
fi
(( ppid == $$ )) || kill -STOP "$ppid" 2>/dev/null || :
pids=( $({ pgrep -P "$ppid" || ps -o pid= --ppid "$ppid" || :; } 2>/dev/null ) )
if [[ -n "${pids[@]:-}" ]]; then
for pid in "${pids[@]}"; do
sf_killtree "$pid" "$sig" 2>/dev/null || :
done
fi
kill "-${sig}" "$ppid" 2>/dev/null || :
(( ppid == $$ )) || kill -CONT "$ppid" 2>/dev/null || :
wait "$ppid" 2>/dev/null || :
}
# kill all child processes of script
function sf_killchildren
{
local _term
_term=$(builtin trap -p TERM)
builtin trap : TERM
sf_killtree $$ TERM;
builtin trap - TERM
builtin eval "$_term"
}
# check if a variable is in an array - usage: sf_inarray "$needle" "${haystack[@]:-}"
function sf_inarray
{
local needle=$1 haystack
shift
for haystack; do
[[ "$needle" != "$haystack" ]] || return 0
done
return 1
}
# join array elements to a string using a given separator
function sf_join
{
if (( $# < 2 )); then
sf_usage "$FUNCNAME <separator> <array>"
return 1
fi
local sep=$1 i
echo -n "$2"
shift 2
for i; do
echo -n "${sep}${i}"
done
echo
}
# make a string safe to sed with
function sf_sedsafe
{
local extended=false
local OPTIND=1 OPTARG OPTERR opt
while getopts ":r" opt; do
case "$opt" in
r) extended=true ;;
[?])
sf_error_unknown_option
return 1
;;
:)
sf_error_missing_argument
return 1
;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
if (( $# != 1 )); then
sf_usage "$FUNCNAME <string>"
return 1
fi
if $extended; then
sed 's/[][\.*^$(){}?+|/]/\\&/g' <<<"$1"
else
sed 's/[][\.*^$/]/\\&/g' <<<"$1"
fi
}
# convert from decimal to binary
function sf_dec2bin
{
local dec=$1 bin=""
local base2=(0 1)
while ((dec)); do
bin="${base2[$((dec % 2))]}$bin"
dec=$((dec/2))
done
[[ -n "$bin" ]] || bin="0"
local octlen=$((${#bin}/8))
! ((${#bin}%8)) || printf "%0$(((octlen+1)*8 - ${#bin}))d" "0"
echo "$bin"
}
# convert from binary to decimal
function sf_bin2dec
{
echo $((2#${1}))
}
# convert an ipv4 to binary
function sf_ipv42bin
{
local bin="" iparray dec
IFS='.' read -r -a iparray <<<"$@"
if ((${#iparray[@]} != 4)); then
sf_error "Not an IPv4 address: $*"
return 1
fi
for dec in "${iparray[@]}"; do
bin+=$(sf_dec2bin "$dec")
done
echo "$bin"
}
# timestamp each line
function sf_stampline
{
while read -r line; do
echo "$(sf_timestamp_short) $line"
done
}
# look for changes between a tar archive and a directory
function sf_tardiff
{
local z=""
local OPTIND=1 OPTARG OPTERR opt
while getopts ":z" opt; do
case "$opt" in
z) z="z" ;;
[?])
sf_error_unknown_option
return 1
;;
:)
sf_error_missing_argument
return 1
;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
if (( $# != 2 )); then
sf_usage "$FUNCNAME <tgz> <dir>"
return 1
fi
file=$1
dir=$2
if ! sf_goodfile -vq "$file" || ! sf_gooddir -vq "$dir"; then
return 1
fi
if ! tar "${z}df" "$file" -C "$dir" . >/dev/null 2>&1; then
return 1
fi
local delta
delta=$(
{
tar "${z}tf" "$file" | grep -v '^\.\/$' | sed 's/\/$//g'
cd "$dir" && find . -mindepth 1
} | sort | uniq -u | sf_wc -c
)
return $(( delta ? 1 : 0 ))
}
# print given fields from output (awk '{print $whatever}')
function sf_fields
{
local fields=() param i line lower upper skip=0 delimiter=" " input_delimiter="$IFS"
local OPTIND=1 OPTARG OPTERR opt
while getopts ":s:d:D:" opt; do
case "$opt" in
s)
skip=$OPTARG
if ! sf_integer -vq -- "$skip"; then
return 1
fi
;;
D) delimiter=$OPTARG ;;
d) input_delimiter=$OPTARG ;;
[?])
sf_error_unknown_option
return 1
;;
:)
sf_error_missing_argument
return 1
;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
while IFS="$input_delimiter" read -ra fields; do
line=""
for param; do
if [[ "$param" =~ ^[[:digit:]]+$ ]]; then
(( param-- )) || :
[[ -z "${fields[param]:-}" ]] || line+="${fields[param]}${delimiter}"
elif
[[ "$param" =~ ^[[:digit:]]+-$ ]] ||
[[ "$param" =~ ^-[[:digit:]]+$ ]] ||
[[ "$param" =~ ^[[:digit:]]+-[[:digit:]]+$ ]]
then
lower=${param%%-*}
lower=${lower:-1}
(( lower-- )) || :
upper=${param##*-}
upper=${upper:-${#fields[@]}}
(( upper--)) || :
for (( i=lower; i<=upper; i++ )); do
[[ -z "${fields[i]:-}" ]] || line+="${fields[i]}${delimiter}"
done
else
sf_error "Invalid field specification: $param"
return 1
fi
done
line=${line%${delimiter}}
read -r line <<<"$line"
[[ -z "${line:-}" ]] || (( skip-- > 0 )) || echo "$line"
done
}
# print lines following a given regex
function sf_lines_from
{
local line print=false skip=0
local OPTIND=1 OPTARG OPTERR opt
while getopts ":s:" opt; do
case "$opt" in
s)
skip=$OPTARG
if ! sf_integer -vq -- "$skip"; then
return 1
fi
;;
[?])
sf_error_unknown_option
return 1
;;
:)
sf_error_missing_argument
return 1
;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
if (( $# != 1 )); then
sf_usage "$FUNCNAME <regex>"
return 1
fi
while IFS='' read -r line; do
$print || ! [[ "$line" =~ $1 ]] || print=true
if $print; then
if (( skip )); then
(( skip-- ))
else
echo "$line"
fi
fi
done
}
# print lines until a given regex occurs
function sf_lines_to
{
local line skip=0
local OPTIND=1 OPTARG OPTERR opt
while getopts ":s:" opt; do
case "$opt" in
s)
skip=$OPTARG
if ! sf_integer -vq -- "$skip"; then
return 1
fi
;;
[?])
sf_error_unknown_option
return 1
;;
:)
sf_error_missing_argument
return 1
;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
if (( $# != 1 )); then
sf_usage "$FUNCNAME <regex>"
return 1
fi
while IFS='' read -r line; do
if (( skip )); then
(( skip-- ))
elif [[ "$line" =~ $1 ]]; then
cat >/dev/null
break
fi
echo "$line"
done
}
# check if given ipv4 is a private address, or print a list of private addresses
function sf_ipv4priv
{
local locnet=(
"127.0.0.0/8"
"10.0.0.0/8"
"172.16.0.0/12"
"192.168.0.0/16"
)
if ! (( $# )); then
printf '%s\n' "${locnet[@]}"
return 0
elif (( $# > 1 )); then
sf_usage "$FUNCNAME <command>"
return 1
fi
local bin ip cmp
bin=$(sf_ipv42bin "$1") || return $?
for ip in "${locnet[@]}"; do
cmp=$(sf_ipv42bin "${ip%%/*}")
cmp=${cmp:0:${ip##*/}}
[[ "${bin:0:${ip##*/}}" != "${cmp:0:${ip##*/}}" ]] || return 0
done
return 1
}
# perform a "which" lookup with a clean path
function sf_which
{(
_sf_verbose=false
local quiet=false
local OPTIND=1 OPTARG OPTERR opt
while getopts ":vq" opt; do
case "$opt" in
v) _sf_verbose=true ;;
q) quiet=true ;;
[?])
sf_error_unknown_option
return 1
;;
:)
sf_error_missing_argument
return 1
;;
esac
done
shift $((OPTIND-1))
if [[ "${1:-}" = "--" ]]; then shift; fi
if (( $# != 1 )); then
sf_usage "$FUNCNAME <command>"
return 1
fi
local result=""
case "$(sf_sysver)" in
*Debian*|*Ubuntu*|*BackTrack*|*Kali*|*Raspbian*|*Arch*|*CentOS*)
if (( BASH_VERSINFO[0] >= 4 )); then
result=$(command -p -v "$1" 2>/dev/null) || :
else
result=$(/usr/bin/env -i bash -l <<< "which ${1}" 2>/dev/null) || :
fi
;;
FreeBSD*)
result=$(/usr/bin/env bash -l <<< "which ${1}") || :
;;
*)
sf_error "Unable to check for \"${1}\" - \"$(sf_sysver)\" is unsupported!"
;;
esac
if [[ -n "${result:-}" ]]; then
$quiet || sf_stdout "$result"
return 0
else
sf_errorv "\"${1}\" was not found on this system!"
return 1
fi
)}
# get the system uptime in seconds
function sf_uptime
{
sf_fields -d '.' 1 </proc/uptime
}
# restart a service
function sf_restartservice
{
if (( $# < 1 )); then
sf_usage "$FUNCNAME <service> [service] ..."
return 1
fi
while [[ -n "${1:-}" ]]; do
case "$(sf_sysver)" in
*Debian*|*Ubuntu*|*BackTrack*|*Kali*|*Raspbian*)
if [[ -e "/etc/init.d/${1}" ]]; then
"/etc/init.d/${1}" restart
else
sf_error "No such service: $1"
return 1
fi
;;
*)
sf_error "${FUNCNAME} has no idea how to restart services on this system!"
sf_stderr "sysver returned: $(sf_sysver)"
exit 1
;;
esac
shift
done
}
# octal permissions
function sf_octperm
{
if (( $# != 1 )); then
sf_usage "$FUNCNAME <file>"
return 1
fi
case "$(sf_sysver)" in
*Debian*|*Ubuntu*|*BackTrack*|*Kali*|*Raspbian*|*Arch*)
printf '%03d\n' "$(stat -c "%a" "$1")"
;;
FreeBSD*)
printf '%03d\n' "$(stat -f "%OLp" "$1")"
;;
*)
sf_error "No idea how to get octal permissions on $(sf_sysver)!"
;;
esac
}
# buffer
function sf_buffer
{
local buffer
buffer=$(base64 -w 0)
base64 -d <<<"$buffer"
}
# netstat
function sf_netstat
{(
local local_address=""
local remote_address=""
local state=""
local pid=""
local listen=""
local OPTIND=1 OPTARG OPTERR opt
while getopts ":lL:p:R:s:" opt; do
case "$opt" in
l) listen="l" ;;
L) local_address=$OPTARG ;;
R) remote_address=$OPTARG ;;
p)
pid=$OPTARG
if ! sf_integer -vq -- "$pid"; then
return 1
fi
pid="${pid}/"
;;
s) state=$(sf_toupper <<<"$OPTARG") ;;
[?])
sf_error_unknown_option
return 1
;;
:)
sf_error_missing_argument
return 1
;;
esac