-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlib.sh
More file actions
executable file
·877 lines (782 loc) · 22.2 KB
/
lib.sh
File metadata and controls
executable file
·877 lines (782 loc) · 22.2 KB
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
#!/bin/bash
# Copyright (C) 2013-2021 Constantine Shulyupin
#
# GPL License
usage="\
lib.sh - Library of shell functions
===
Usage:
Load commands to shell:
. lib.sh
Run a command with subshell:
lib.sh <command> <arguments...>
"
###############################################################################
# Common stuff
MYSHELL=`/bin/ps -p $$ -o command=| sed "s:$0::;s:busybox ::"`
export tab=$'\t'
export NUMCPUS=`grep -c '^processor' /proc/cpuinfo`
unset usage
unset cmds
declare -A usage
declare -a cmds
cmd()
{
cmds+=($1)
usage[$1]="$2"
}
cmd lib-help "shows help for Lib.sh"
lib-help()
{
echo -e "List of available commands:\n"
for i in ${cmds[*]}
do
echo "$i - ${usage[$i]}"
done
}
lib-snippets()
{
for i in "${!usage[@]}"
do
(
echo -e "$i - ${usage[$i]}\n====\n\n"
echo -e "\`\`\` bash"
if [ $(type -t $i) == alias ]; then
a=$(type $i); echo alias ${a/ is aliased to \`/=\'}
else
#type "$i" | (read; cat)
awk "/cmd $i/{f=1;next}; { if (f && /$^/)exit}; f" lib.sh
fi
echo "\`\`\`"
) > "snippets/$i.md"
done
}
###############################################################################
# Short useful definitions and aliases
GREP_OPTIONS="--devices=skip --color=auto " # avoid hanging grep on devices
export GREP_COLORS='ms=01;38:mc=01;31:sl=02;38:cx=:fn=32:ln=32:bn=32:se=36' # print matched text in bold
export HISTIGNORE="&:ls:[bf]g:exit"
cmd ps-all "lists all processes"
alias ps-all='ps -AF'
cmd ps-threads "lists processes with threads"
alias ps-threads="ps -ALf"
cmd ps-recent "lists resent user processes"
alias ps-recent='ps -x -o etime,pid,comm,%cpu,%mem --sort etime | head -n$((LINES-2))'
cmd ps-tree "lists process tree via ps, see also pstree -p"
alias ps-tree="ps -ejH"
cmd ps-cpu "lists most CPU consuming processes"
alias ps-cpu="ps -e -o pcpu,pid,comm --sort -%cpu | head -n 10"
cmd ps-mem "lists most memory consuming processes"
alias ps-mem="ps -e -o pmem,vsz,rss,pid,comm --sort -%mem | head -n 10"
alias ps-cpu-mem="ps -e -o pcpu,pmem,rss,pid,comm --sort -%cpu,-%mem | head -n 10"
cmd default-eth "provides default Ethernet interface"
alias default-eth='ip route | awk "/default/ { print \$5 }"'
cmd external-ip "Provides external IP"
alias external-ip="dig +short myip.opendns.com @resolver1.opendns.com"
cmd ps-wchan "shows what processes are waiting for, used in debugging blocked processes"
alias ps-wchan="ps -e -o pid,comm,wchan"
cmd ls-size "list files with sizes in bytes, shorter than ls -l"
#alias ls-size='ls -s --block-size=1 -1'
#alias ls-size='stat -c "%s$tab%n"'
ls-size() { stat -c "%s$tab%n" `\ls "$@"`; }
cmd mplayer-rotate-right "play video rotated right, used to play vertically captured videos"
alias mplayer-rotate-right="mplayer -vf rotate=1"
cmd hist "handy history, up to one screen length"
alias hist='history $((LINES-2))'
cmd deb-list "list content of specified deb file"
alias deb-list="dpkg-deb --contents"
cmd quotation-highlight "highlight text in quotation marks (\"quotation\")"
ansi_rev=$'\e[7m'
alias quotation-highlight=' sed "
s|\\\\\\\\|:dbs:|g;
s|\\\\\"|:bsq:|g;
s|\\\\\"|:quotation:|g;
s|\"\([^\"]*\?\)\"| $ansi_rev\1$reset_color |g;
s|:quotation:|\\\\\"|g;
s|:bsq:|\\\\\\\"|g;
s|:dbs:|\\\\\\\\|g"'
cmd keyboard-shortcuts "bash keyboard shortcuts. See also man readline."
alias keyboard-shortcuts='(bind -P | grep -v "is not bound" | nl |
sed "
s| can be found on|:|;
s|.$||;
s|, \+| |g;
s|\\\C-|^|g
s|\\\e|+|g;" \
| pr --omit-header --expand-tabs --columns=2 -w $COLUMNS \
| expand; \
echo \"^\" = Ctrl, \"+\" = Escape) | quotation-highlight '
cmd tcpdump-text "tcpdump of payload in text"
alias tcpdump-text="sudo tcpdump -l -s 0 -A '(((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0) and'"
cmd make-debug "verbose make"
alias make-debug="remake --debug=bv SHELL='/bin/bash -vx' "
# git helpers
cmd git-diff "handy git diff"
alias git-diff='git diff --relative --no-prefix -w'
alias repo-braches='repo forall -p -c git for-each-ref --format="%(refname:short)" refs/heads/*'
cmd repo-braches "list git branches of repo subprojects"
cmd git-prompt "sets shell prompt to show git branch"
git-prompt()
{
PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
}
cmd git-fixup "interactive fix up of specified number of last git commits"
git-fixup()
{
git rebase -i HEAD~$1 .
}
cmd git-ign-add "add files' names with path to appropriate .gitignore list"
git-ign-add()
{
for a in $*; do
echo "$a"
(cd `dirname "$a"`; \ls -d `basename "$a"` -1 >> .gitignore; git add .gitignore )
done
}
cmd log "safely prints messages to stderr"
log()
{
# Note: echo "$@" > /dev/stderr - resets stderr
( 1>&2 echo "$@" )
}
cmd trap-err "traps command failures, print return value and returns, better than set -o errexit"
trap-err()
{
trap '(1>&2 echo -e $"\e[2;31mFAIL \e[0;39m ret=$? ${BASH_SOURCE[0]}:${LINENO} ${FUNCNAME[*]}";)' ERR
}
trap-err-return()
{
trap '(1>&2 echo -e $"\e[2;31mFAIL \e[0;39m ret=$? ${BASH_SOURCE[0]}:${LINENO} ${FUNCNAME[*]}"; return $ret; )' ERR
}
trap-err-test()
{
trap-err
echo 1
false
echo 2
trap '' ERR
}
###############################################################################
# Shell functions
cmd system-status-short "shows short summary of system resources (RAM,CPU) usage"
system-status-short()
{
inxi -M
inxi
grep -e MemTotal: -e MemAvailable: /proc/meminfo
paste <(mpstat|grep %usr|sed "s/ \+/\n/g") <(mpstat|grep all|sed "s/ \+/\n/g") | \grep -e idle -e iowait -e sys
ps-cpu
ps-mem
# blocked
ps axo stat,pcpu,pid,comm | grep ^D
}
cmd system-status-long "shows long system status and statistics by running various system utilities"
system-status-long()
{
grep "" /etc/issue /etc/*release
sed 's/\([^ =]*\)=*\([^ ]*\)\s*/\1\t\2\n/g' /proc/cmdline | column -t|sort
echo
getconf LONG_BIT
top -bn1 | head --lines 20
echo
free -m
echo
iostat -m
echo
mpstat # pkg sysstat
echo
vmstat -S M -s
echo
df --all --human-readable
echo
sudo -n parted -l || sudo -n flisk -l
echo
sudo -n dmidecode
echo
sudo -n lshw -short
echo
lsblk
echo
blkid
echo
lscpu
echo
ip addr
echo
ip route
echo
lsusb
echo
lspci
echo -e "Biggest packages:"
dpkg-query -W -f='${Installed-Size} ${Package} - ${Description}\n' | sort -n | tail -n 10
echo -e "Old unused files:"
find / -mount -type f -atime +1000 -ls 2> /dev/null
grep -q -w "127.0.0.1.*$(hostname)" /etc/hosts || echo warning: no hostname for localhost
}
cmd shell-type "tries to identify type of current shell"
shell-type()
{
# adopted from http://stackoverflow.com/questions/5166657/how-do-i-tell-what-type-my-shell-is
# see also http://www.in-ulm.de/~mascheck/various/whatshell/whatshell.sh.html
# also can be useful:
# ps -p $$ -o comm=
# ps -p $$ -o command=
if test -n "$ZSH_VERSION"; then
echo zsh
elif test -n "$BASH_VERSION"; then
echo bash
elif test -n "$KSH_VERSION"; then
echo ksh
else
/bin/ps -p $$ -o command=| sed "s@$0@@;s@busybox @@"
fi
}
cmd ps-of "specified process info"
ps-of()
{
# ps u -C "$1"
ps u `pidof "$@"`
}
cmd proc-mem-usage "returns percentage memory usage by specified process"
proc-mem-usage()
{
ps h -o pmem -C "$1"
}
cmd dir-diff "compare listings of two specified directories"
dir-diff()
{
find "$1" -type f -printf "%P\n" | sort > "$1/list.tmp"
find "$2" -type f -printf "%P\n" | sort > "$2/list.tmp"
kdiff3 "$1/list.tmp" "$2/list.tmp"
}
cmd retry "retry argument operation till success"
retry()
{
# see also "watch"
while ( ! "$@" ) do
log retry
sleep 1
done
}
exclude_dirs=("*.log" \*.gcov \*.gcda
"*_icgraph.*" "*_cgraph.*" "inherit_graph_*.*" "*_incl.*" html
tmp .git .repo .svn "*._comment" .dropbox.cache third-party out
intermediates .gradle .idea "_build_*" .cxx Debug CMakeFiles build)
if [ "$BASH_VERSION" ]; then
exclude_dirs_with_coma="$(IFS=','$IFS; eval echo "${exclude_dirs[*]}")"
grep_exclude_dirs="$(eval echo "'--exclude-dir='"{$exclude_dirs_with_coma} )"
find_exclude_body="$(eval echo "' -o -name '"{$exclude_dirs_with_coma})"
find_exclude="( ( -false $find_exclude_body ) -a -prune ) -o "
else
exclude_dirs_with_coma=
grep_exclude_dirs=
find_exclude_body=
find_exclude=
fi
exclude_dir_add()
{
while [ -n "$1" ]; do
exclude_dirs_with_coma+=",$1"
grep_exclude_dirs+=" --exclude-dir=$1"
find_exclude_body+=" -o -name $1"
shift
done
find_exclude="( ( -false $find_exclude_body ) -a -prune ) -o "
}
cmd duplicates 'finds duplicate files. To follow symbolic links run duplicate -L $DIR'
duplicates()
{
# Features:
# * Fast - because it checks sizes first
# and filters same linked files by checking inode (%i)
# * Sorts files by size to help you to delete biggest files first
#
# Troubleshooting:
# on out of memory define TMPDIR
#
set -o noglob
find "$@" $find_exclude -type f \
-printf "%10i\t%10s\t%p\n" \
| sort -n \
| uniq --unique -w10 \
| cut -f 2,3 | sort -n \
| uniq --all-repeated -w 10 \
| cut -f 2 \
| perl -pe "s/\n/\0/g" \
| xargs -0 -i{} sha1sum "{}" | sort \
| uniq --all-repeated=separate -w32 \
| cut -d ' ' -f 3-
set +o noglob
}
cmd for-each "applies an operation to set of arguments one by one"
for-each()
{
op=$1
shift
for arg in "$@"; do
eval "$op" \"$arg\"
done
}
cmd str "readable string manipulations: ltrim, ltrim-max, rtrim, rtrim-max, subst, subst-all"
str()
{
case $1 in
(ltrim) echo "${2#$3}" ;;
(ltrim-max) echo "${2##$3}";;
(rtrim) echo "${2%$3}";;
(rtrim-max) echo "${2%%$3}";;
(subst) echo "${2/$3/$4}";;
(subst-all) echo "${2//$3/$4}";;
(ext) echo "${2#*.}";;
(rtrim-ext) echo "${2%%.*}";; # path without extension
(base) # just filename without path and extension
expr \
match "$2" '.*/\(.*\)\.tar' \| \
match "$2" '.*/\(.*\)\.' \| \
match "$2" '.*/\(.*\)'
;;
esac
# More: https://www.tldp.org/LDP/abs/html/string-manipulation.html
}
cmd postfix-extract "return filename postfix: path/name[-_]postfix.ext -> postfix"
postfix-extract()
{
a=${1%.*}
echo "${a##*[-_]}"
}
cmd unzip-dir "handy unzip to directory with name of zip-file"
unzip-dir()
{
unzip "$@" -d `str base "$1"`
}
cmd mac-to-ip "looks for LAN IP for MAC"
mac-to-ip()
{
(
(for b in $(ip addr ls | awk '/inet .* brd/ {print $4}'); do
ping -q -c 1 -b $b &> /dev/null
done ) &
) 2> /dev/null
while ! a=$(arp -n | grep -i "$1"); do sleep 1; log 'waitig' ; done;
echo "$a" | (read a1 a2; echo $a1)
}
cmd ip-to-mac "show MAC address for specified IP in LAN"
ip-to-mac()
{
if which arping > /dev/null; then
arping -c 1 "$1" 2> /dev/null | perl -ne '/.*\[(.*)\].*/ && print "$1\n"'
else
ping -c 1 -w 1 "$1" &> /dev/null
arp -na | grep "$1" | cut -f 4 -d ' '
fi
}
cmd fs-usage "show biggest directories and optionally files on a filesystem, for example on root: fs-usage -a /"
fs-usage()
{
du --time --one-file-system "$@" | sort -n | tail -n $((LINES-2)) | while read s n; do echo $(numfmt --to=iec-i $((1024*s))) $n; done
df "$@"
}
cmd PATH-append "appends argument to PATH, if required"
PATH-append()
{
if [[ ":$PATH:" == *":$1:"* ]]
then
echo "$1 is already in path"
else
export PATH="$PATH:$1"
fi
}
cmd PATH-insert "inserts argument to head of PATH, if required"
PATH-insert()
{
if [[ ":$PATH:" == *":$1:"* ]]
then
echo "$1 is already in path"
else
export PATH="$1:$PATH"
fi
}
cmd PATH-remove "removes argument from PATH"
PATH-remove()
{
PATH=$(echo ":$PATH:"| sed "s|:$1:|:|g" | sed "s|::||g;s|^:||;s|:$||")
}
cmd PATH-append "prints PATH in readable format"
PATH-show()
{
echo $PATH | sed "s/:/\n/g"
}
cmd gcc-set "append a string to a file if it not yet present there"
file-append-once()
{
mkdir -p $(dirname "$1")
grep --quiet --line-regexp --fixed-strings "$2" "$1" && return
test -w "$1" && echo "$2" >> "$1" || echo "$2" | sudo tee -a "$1"
}
cmd gcc-set "set specified [cross] compiler as default in environment"
gcc-set()
{
#export PATH=/usr/sbin:/usr/bin:/sbin:/bin:
PATH-append $(dirname $(which "$1"))
export CROSS_COMPILE=$(expr match "$(basename $1)" '\(.*-\)')
export CC=${CROSS_COMPILE}gcc
export AR=${CROSS_COMPILE}ar
export LD=${CROSS_COMPILE}ld
export AS=${CROSS_COMPILE}as
export CPP=${CROSS_COMPILE}cpp
export CXX=${CROSS_COMPILE}c++
echo Using:
which "$CC"
mach=`$CC -dumpmachine`
export ARCH=${mach%%-*}
PS1='$ARCH \w \$ '
$CC -v 2>&1 | grep 'gcc version'
}
cmd replace "replaces substring arg1 to substring arg2 in directory arg3"
replace()
{
test "$1" || { echo ${usage[replace]}; return; }
grep "$1" "$3" \
-rl --exclude .orig --exclude .git --binary-files=without-match --exclude-dir=.svn --exclude-dir=.git -P \
| xargs sed -i "s|$1|$2|g"
}
https-to-git()
{
a=$(expr match "$1" "^https://github.com/\(.*\)") && { echo git@github.com:$a; return;}
echo "$1"
}
cmd get-source "download and unpack an open source tarball"
get-source()
{
local a=$(https-to-git "$1")
case $a in
(git* | *.git | https://github.com/*) git clone $a ;;
(svn*) git checkout $a ;;
(*)
fn=$(basename $a)
n=${fn%%.tar.*}
! test -f ~/Downloads/"$fn" && (expr match "$a" "^http" || expr match "$a" "^ftp" ) > /dev/null && wget -P ~/Downloads/ "$a"
[ -e "$n" ] || aunpack -q ~/Downloads/"$fn"
esac
}
cmd gnu-build "universal complete build and install of gnu package"
gnu-build()
{
[ "$CC" ] || CC=gcc
[ "$1" ] && get-source $1 || n=.
shift
pushd $n
if [ -d debian ]; then
# apt-get build-dep
dpkg-buildpackage -rfakeroot -uc -b
fi
test -f CMakeLists.txt && cmake -B build && make -C build
test configure.ac -nt configure && ./autogen.sh -q
test -e configure || autoreconf --install # configure.ac configure.in
if [ -e configure ]; then
configure_opt="$configure_opt_init -q"
if [ -n "$DESTDIR" ]; then
configure_opt+=" --prefix=/ --includedir=/include "
fi
configure_opt+=" CPPFLAGS='${CPPFLAGS}'"
configure_opt+=" LDFLAGS='${LDFLAGS}'"
if [ -n "${CROSS_COMPILE}" ]; then
configure_opt+=" --host=${CROSS_COMPILE%-}"
fi
test "${staging}" && configure_opt+=" --with-sysroot=${staging}"
configure_opt+=" $* "
mkdir -p $($CC -dumpmachine)-build
pushd $_
test -e Makefile || ( echo "Configuring $configure_opt" && eval ../configure $configure_opt )
make -j$NUMCPUS --load-average=$NUMCPUS -ws
# && make -k install || sudo -H make -k install
ret=$?
popd
fi
ls
if [ -e Makefile.PL ]; then
perl Makefile.PL
make
sudo make -k install
ret=$?
fi
popd
return $ret
}
cmd alternative-config-build "build of package, alternatively to gnu-build"
alternative-config-build()
{
[ "$CC" ] || CC=gcc
get-source $1
shift
mkdir -p $n/$($CC -dumpmachine)-build~ # '~' to skip by lndir
pushd $_
lndir -silent ..
./configure -q "$@"
make -j$NUMCPUS --load-average=$NUMCPUS -ws &&
make install
ret=$?
popd
return $ret
}
cmd build-env "configure staging build environment"
build-env()
{
staging=$(readlink --canonicalize $1)
PKG_CONFIG_DIR= #https://autotools.io/pkgconfig/cross-compiling.html
PKG_CONFIG_SYSROOT_DIR=$staging
#export PKG_CONFIG_PATH=$staging/lib/pkgconfig
PKG_CONFIG_LIBDIR=$PKG_CONFIG_SYSROOT_DIR/lib/pkgconfig
DESTDIR=$staging # used by make install
CPPFLAGS=-I${staging}/include
LDFLAGS=-L${staging}/lib
LDFLAGS+=' '-Wl,-rpath-link=${staging}/lib
export staging PKG_CONFIG_DIR PKG_CONFIG_SYSROOT_DIR DESTDIR CPPFLAGS LDFLAGS
}
cmd glib-arm-build "demonstration of arm compilation of glib from the scratch"
glib-arm-build()
{
gcc-set /usr/bin/arm-linux-gnueabi-gcc
build-env staging-$($CC -dumpmachine)
alternative-config-build http://zlib.net/zlib-1.2.8.tar.gz --prefix=/
gnu-build ftp://sourceware.org/pub/libffi/libffi-3.2.1.tar.gz
cp -a ${staging}/lib/libffi-*/include ${staging}/
export glib_cv_stack_grows=no glib_cv_uscore=no ac_cv_func_posix_getpwuid_r=yes ac_cv_func_posix_getgrgid_r=yes
gnu-build http://ftp.gnome.org/pub/gnome/sources/glib/2.48/glib-2.48.1.tar.xz --with-pcre=internal
file -L staging-$($CC -dumpmachine)/lib/libglib-2.0.so
return $?
}
cmd staging-dir-fix "fix parameter libdir in *.la files in staging cross-compilation directory"
staging-dir-fix()
{
sed -i "s|^libdir='//\?lib'|libdir='`readlink --canonicalize "$1"`/lib'|" \
`grep --no-messages --recursive --files-with-matches --include *.la "libdir='//\?lib" "$1"`
grep -r --include *.la "libdir=" "$1"
}
cmd mem-drop-caches "drop caches and free this memory. Practically not required"
alias mem-drop-caches="sync; echo 3 | sudo tee /proc/sys/vm/drop-caches"
cmd gdb-print-prepare "utility to print C,C++ variables and structs at runtime"
gdb-print-prepare()
{
if [[ $# == 0 ]]; then
cat <<-EOF
Usage:
Mark print points in C or C++ sources with pseudo comment:
// gdb_print(big_struct)
gdb-print-prepare \$src > app.gdb
gdb --batch --quiet --command=app.gdb \$app
See file gdb-print-demo.c for example.
EOF
return
fi
cat <<-EOF
set auto-load safe-path /
EOF
grep --with-filename --line-number --recursive --only-matching 'gdb_print(.*)' $1 | \
while IFS=$'\t :;()' read file line func var rest; do
cat <<-EOF
break $file:$line
commands
silent
where 1
echo \\n$var\\n
print $var
cont
end
EOF
done
cat <<-EOF
run
echo ---\\n
EOF
}
cmd wget-as-me "Run wget with cookies from firefox to access authenticated data"
wget-as-me()
{
sqlite3 -separator "$tab" $(ls -1t $HOME/.mozilla/firefox/*.default*/cookies.sqlite | head -1) \
'select host, "TRUE", path, "FALSE", expiry, name, value from moz_cookies' \
> ~/.mozilla/cookies.txt
wget -q --load-cookies ~/.mozilla/cookies.txt "$@"
ret=$?
#( 1>&2 echo echo ret=$ret )
return $ret
}
cmd calc "calculate with bc specified floating point expression"
calc()
{
# see also http://www.isthe.com/chongo/tech/comp/calc/
echo "scale=4;" "$@" | bc
}
cmd md5sum-make "create md5 files for each specified file separately"
md5sum-make()
{
while [ -n "$1" ]; do
md5sum "$1" > "$1.md5"
echo "$1.md5"
shift
done
}
red_color=$'\033[31m'
green_color=$'\033[32m'
reset_color=$'\033[m'
cmd check "runs verbosely specified command and prints return status"
check()
{
echo -n "Running: $@ : "
eval "$@" && { let successes+=1; echo -e "$? ${green_color}OK$reset_color"; } || { let fails+=1; echo -e "$? ${red_color}Fail $reset_color"; }
}
google-chrome-install()
{
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome-stable_current_amd64.deb
}
# used in lib-sh-demo only
v()
{
echo ">" "$@"
eval "$@"
}
# used in lib-sh-demo only
eq()
{
a="$1"
echo -n "$a "
shift
if [ "$a" == $(eval "$@") ]; then echo -n '= '; else echo -n '!= '; fi
echo "$@"
}
cmd lib-sh-demo "run lib.sh functions for demonstration and testing"
lib-sh-demo()
{
eq '4.tar.gz' str ext '1/2/3.4.tar.gz'
eq '3' str base '1/2/3.4.tar.gz'
v postfix-extract path/name-postfix.ext
v for-each echo aaa bbb ccc
mkdir -p dup/sub
echo 1 > dup/1
cp dup/1 dup/1.1
cp dup/1 dup/sub/
echo 2 > dup/2
v duplicates dup
check true
check false
#not supported
#v 'wget-as-me "http://mail.google.com/mail?nocheckbrowser&ui=html" -O- \
# | lynx -stdin -dump -width=$COLUMNS | grep ^Inbox -A 10'
}
cmd doxygen-bootstrap "generic handy doxygen wrapper"
doxygen-bootstrap()
{
if [ ! -e Doxyfile ]; then
cat > Doxyfile <<-EOF
PROJECT_NAME = "$(basename $PWD)"
EXTRACT_ALL = YES
EXTRACT_STATIC = YES
RECURSIVE = YES
EXCLUDE = html
GENERATE_TREEVIEW = YES
GENERATE_LATEX = NO
HAVE_DOT = YES
DOT_FONTSIZE = 15
CALL_GRAPH = YES
CALLER_GRAPH = YES
#INTERACTIVE_SVG = YES
DOT_IMAGE_FORMAT = svg
#DOT_TRANSPARENT = YES
DOT_MULTI_TARGETS = NO
DOT_CLEANUP = NO
OPTIMIZE_OUTPUT_FOR_C = YES
DOT_FONTNAME = Ubuntu
#CASE_SENSE_NAMES = YES
SOURCE_BROWSER = YES
QUIET = yes
REFERENCED_BY_RELATION = yes
REFERENCES_RELATION = yes
EOF
# command doxygen -u
fi
cat Doxyfile | doxygen -u - > Doxyfile.explained
cat Doxyfile | doxygen -s -u - > Doxyfile.expanded
command doxygen "$@" 2> doxygen.log
xdg-open html/index.html || firefox html/index.html
}
cmd load-watch "kills memory and cpu hogs when load average is too high"
csi=$'\e['
load-watch()
{
local nproc=$(getconf _NPROCESSORS_ONLN)
echo
while true; do
echo -n ${csi}A
echo -n $(date "+%T $SECONDS ") " "
local load
free=$( grep MemAvailable: /proc/meminfo | (read a b c d e; echo $((b/1024))) )
IFS="/ " read -a load < /proc/loadavg
local loadproc=$((10#${load/./}00/${nproc}00)) # '10#' is to force decimal, because 'load' starts from 0
local pcpu=$(echo $(ps --no-headers -e -o pid,comm,pcpu --sort -%cpu | head -n 1))
local pmem=$(echo $(ps --no-headers -e -o pid,comm,pmem --sort -%mem | head -n 1))
echo -n "load=$load $loadproc% running=${load[3]} free=$free MB, $pcpu% cpu, $pmem% mem"
echo "${csi}K"
test -w /proc/${pcpu%% *}/oom_score_adj && echo 1000 > /proc/${pcpu%% *}/oom_score_adj
test -w /proc/${pmem%% *}/oom_score_adj && echo 1000 > /proc/${pmem%% *}/oom_score_adj
if [ \( ${load[3]} -gt $((1 * ${nproc})) \) -a \( $loadproc -gt 200 \) ]; then
echo killing "${pcpu} "
echo
kill "${pcpu%% *}"
fi
if [ $free -lt 200 ]; then
echo killing "${pmem} "
echo
kill "${pmem%% *}"
fi
SECONDS=0
read -t 5
done
}
load-monitor()
{
local nproc=$(getconf _NPROCESSORS_ONLN)
echo
while sleep 1; do
local load
IFS="/ " read -a load < /proc/loadavg
echo "${csi}K"
if [ ${load[3]} -gt $((${nproc})) ]; then
date "+%y-%m-%d %T"
free=$( grep MemAvailable: /proc/meminfo | (read a b c d e; echo $((b/1024))) )
local loadproc=$((10#${load/./}00/${nproc}00)) # '10#' is to force decimal, because 'load' starts from 0
echo -n "load=$loadproc% running=${load[3]} free=$free MB"
ps -e -o pcpu,pmem,pid,comm,args:5 --sort -%cpu,-%mem | cut -c -100 | head -n 10
echo
fi
done
}
cmd dts-tags "extacts tags (ctags format) from device tree source files"
dts-tags()
{
grep -oH '\w\+:' "$@" | awk -F: '{print $2"\t"$1"\t/"$2":"}' | LC_ALL=C sort
}
security-checks()
{
echo GOOD:
egrep -i '^PubKeyAuthentication yes|^PasswordAuthentication no' <(sshd -T 2> /dev/null) /etc/ssh/sshd_config
echo BAD:
egrep -i '^PasswordAuthentication yes|^PermitRootLogin yes|^PermitEmptyPasswords yes' <(sshd -T 2> /dev/null) /etc/ssh/sshd_config
echo -- done
echo Lynis:
sudo lynis audit system
echo Chkrootkit:
sudo chkrootkit -q
}
if [ -n "$*" ]; then
eval "$*" # execute arguments
echo $* finished, ret=$?
else
if [ "$0" != "$BASH_SOURCE" ]; then
echo Lib.sh functions are loaded into the shell environment
else
echo Lib.sh - a library of shell utility functions
echo To get help run \"$BASH_SOURCE lib-help\"
fi
fi