-
Notifications
You must be signed in to change notification settings - Fork 151
/
utils.sh
1024 lines (593 loc) · 18.6 KB
/
utils.sh
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
## about
# This file is being cut up into smaller files.
# Distribution specific installation procedures are put outside of this section.
# For a summary of up to level 2 header: `grep -E '^[[:space:]]{0,4}## ' %`.
## configuration
## Ubuntu
## jockey
# Additional drivers : non-free vendors
# List:
jockey-text --list
# Enable from list. E.g.: xorg:fglrx_updates:
jockey-text --enable=$DRIVER
## Programming
## pkg-config
#info is contained in "$PKG_NAME.pc" files located mainly under:
#/usr/share/pkgconfig/
#/usr/lib/i386-linux-gnu/pkgconfig/
#a part of program installation may be to put files there
#usage in in a makefile:
CFLAGS=$(shell pkg-config --cflags pkgname)
LIBS=$(shell pkg-config --libs pkgname)
## source-highlight
# Takes in source files and produces highlighted output in one of the formats:
# - html
# - ansi terminal escape sequences
# - pdf
# List all languages supported:
source-highlight --lang-list
# Generate an `a.html` highlighted version of `a.py`:
source-highlight a.py
## pygments
#python package for multi language syntax coloring.
#take python source, output colored html:
pygmentize -O full -o test.html test.py
firefox test.html &
#-O: options.
#full is required here, otherwise there would be no header,
#and the style info would not be put in the html
#input and output formats here were inferred from extension,
#but can be explicitly set too.
## c99
#POSIX C99 compiler!
#On Linux as of 2013, acts as a simple GCC frontend.
#At first glance `gcc -std=c99` is largely compatible with the POSIX c99.
## fort77
#POSIX fortran compiler.
## text
## yes
# coreutils
# Repeat an output forever!
yes
#y
#y
#y
#...
yes a b c
#a b c
#a b c
#a b c
#...
# Good for programs that keep asking for keyboard confirmations
# and which have no command line way of given them at invocation time:
yes | timeout 1 cat
## nl
# POSIX 7
# CAT LInes, number non-empty ones:
nl "$f"
## fmt
# coreutils.
# Wrap lines, but don't cut words
[ `echo "a bcd" | fold -w 2` = $'a\nbcd' ] || exit 1
## split
# coreutils package.
# Split files into new smaller files of same size
echo -n abc > f
split -db1 f p
split -dn3 f p
[ "$(cat p00)" = 'a' ] || exit 1
[ "$(cat p01)" = 'b' ] || exit 1
[ "$(cat p02)" = 'c' ] || exit 1
# Existing files are overwritten:
# Options:
# - `d`: uses number suffixes, otherwise, uses letters aa, ab, ac, ...
# - `b`: bytes per file
# - `n`: number of files
## csplit
# corutils.
# Split files into new smaller files at lines that match given EREs.
# Matching lines are kept.
printf '0\naa\n1\naa\n2\n' > f
csplit f '/^a/' '{*}'
[ `cat xx00` = 0 ] || exit 1
[ `cat xx01` = $'aa\n1' ] || exit 1
[ `cat xx02` = $'aa\n2' ] || exit 1
## Path operations
## basename
## dirname
# POSIX 7
[ "$(dirname "/path/to/dir/or/file")" = "/path/to/dir/or" ] || exit 1
[ "$(basename "/path/to/dir/or/file")" = "file" ] || exit 1
[ "$(dirname "/")" = "/" ] || exit 1
[ "$(basename "/")" = "/" ] || exit 1
# Extensions can be extracted naively with variable expansion, but it is not trivial to make it work for dot files.
## moreutils
# Extra base Linux utils.
sudo aptitude install moreutils
## sponge
# solves the input to output problem problem.
# setup:
printf '0\n1\n' > a
# Fails:
grep 0 a | cat > a
[ "`cat a`" = '' ] || exit 1
# Works:
grep 0 a | sponge a
[ "`cat a`" = '0' ] || exit 1
## vipe
# Use editor (aka vim =)) in the middle of a pipe:
EDITOR=vim
seq 10 | vipe | less
a="`seq 10 | vipe`"
echo "$a"
# Uses editor environment variable to determine editor.
# In Ubuntu, this is set by default to vim in bashrc.
# This is a good way to get user input that might be large, e.g. git commit messages.
a="`echo -e "\n#lines starting with '#' will be ignored" | vipe | grep -Ev '^#' `"
echo "$a"
## Character encoding
## Chinese
# - Guobiao is mainly used in Mainland China and Singapore. Named as `GB\d+`
# - Big5, used in Taiwan, Hong Kong and Macau
# `file` does not work properly for chinese
## dos2unix
# CR LF to CR.
# In place:
echo -e 'a\r\nb\r\n' > a.txt
dos2unix a.txt
[ "`cat a.txt`" = $'a\nb\n' ] || exit 1
# Does some smart heuristic things like skipping binary files and FIFOs, so better than `sed`.
## enca
# Detect and convert international encodings.
# Guess encoding:
enca a.txt
# This may not work if you don't give the expected language as input.
# View available languages:
enca --list languages
# Tell enca that the file is in chinese:
enca -L zh a.txt
# You give languages as locales
# (i think as 2 letter iso 639-1 codes <http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes> since only `zh` worked for chinese)
## convmv
# mv converting encodings
## system info
## CPU
## Processor
## mpstat
# Processor related stats:
mpstat
## nproc
# Number of processing unites (= cores?).
# coreutils
nproc
## hwinfo
sudo aptitude install -y hwinfo
hwinfo | less
## sar
# Long term performance statistics.
# You must run this as a cronjob:
crontab -e
# Paste:
*/5 * * * * root /usr/lib/sa/sa1 1 1
# CPU usage
sar -u
# Disk IO stats:
sar –d
# Network stats:
sar -n DEV | more
sar -n SOCK |more
## hardware specs
## bus
## usb
# New: usb 3.0
# Old still existing: usb 2.0
# Current uses: mouse, keyboard, external hard disks, external cd, flash storage devices.
# Several device classes.
# Several connector types: Standard-A, Standard-B, Micro-B, Mini-B
# <http://en.wikipedia.org/wiki/File:Usb_connectors.JPG>
#3.0:
# - full duplex
# - 8 pins
# - voltage: 5 V
# - power: max 0.9 A (5V)
# - signaling rate: 5 Gbit/s (Super Speed mode)
# - maximal cable length: 5 meters
## differentiate from usb 2.0
# - 3.0 tipically blue while 2.0 black
# - 3.0 has 8 pins instead of 4
# - ss for super spped may be written
# - <http://www.usb3.com/usb3-info.html>
## firewire
## ethernet
## lshw
# Show lots of hardware specs, including networing, USB, CPU.
sudo lshw
## Processes
## pwdx
# Print current working directory of given process:
pwdx $pid
## trap
# Capture signals.
trap "echo a" SIGINT SIGTERM
# Now Ctrl-C away and notice `a` get printed.
## bg
#POSIX 7
#bg %3
#starts running job 3 which was stopped on background
#bg
#bg %+
#bg %%
#last bg job [+]
#bg %-
#before last bg job [-]
## fg
#POSIX 7
#fg %3
#starts running job 3 which was on background on foreground
#fg
#last job
## disown
# Remove job 3 from list of sub jobs.
# Closing bash will not kill it anymore.
#vlc 100 &
#vlc 100 &
#vlc 100 &
#disown %3
## flock
# Puts an advisory file lock on given file while a command executes:
touch a
flock a sleep 5 &
# TODO sample usage.
## prtstat
#TODO
## peekfd
#TODO
## ipcs
# List info on inter process communication facilities:
ipcs
# Shows:
# - shared mem
# - semaphores
# - message queues
## ipcrm
# Remove IPC facility.
## vmstat
# Memory, sway, io, cpu
# Run every 1s, 100 times.
vmstat 1 100
# Vmstat procs Section
#r field: Total number of runnable process
#b field: Total number of blocked process
#Memory section
#Swpd field: Used swap space
#Free field: Available free RAM
#Buff field: RAM used for buffers
#Cache field: RAM used for filesystem cache
#Swap Section
#Si field: Amount of memory swapped from disk per second
#So field: Amount of memory swapped to disk per second
#IO Section
#Bi field: Blocks received from disk
#Bo field: Blocks sent to disk.
#System Section
#In field: Number of interrupts per second.
#move you mouse and see this go up!
#Cs field: Number of context switches per second.
#CPU Section
#Us field: Time spend running user code. (non-kernel code)
#Sy field: Time spent running kernel code.
#Id field: Idle time.
#Wa field: Time spent waiting for the IO
## files
## cd
#POSIX
#go to dir
mkdir d
cd d
pwd
#goto home dir:
cd
cd ~
#go back to last dir:
cd -
#cannot go 2 dirs back: goes back an forth between current and last dir.
#The following simply goes to current dir:
cd -
cd -
#-a : (all) show hidden files
#-h : human readable filesizes
#-l : long. one per line, lots of data.
cd -alh
#PATH variable for cd!
CDPATH=/usr/:~
cd
mkdir a
mkdir b
cd b
cd a
pwd
#~/a
## touch
# POSIX
# Create file if does not exist.
# Update modify date to present if it exists.
touch f
## mkdir
#POSIX
#make dirs
#make a dir:
mkdir "$d"
#no error if existant:
mkdir d
mkdir -p d
#make parent dirs if not existent:
mkdir -p a/b/c/d
#-m: set mode of new dir (permissions)
mkdir -m 1777 d
[ `stat -c "%A" d` = 'drwxrwxrwt' ] || exit 1
## mv
# POSIX
# Move or rename files and dirs.
## files
# If dest does not exist, move the file to it:
mkdir d
touch d/a
mkdir d2
mv d/a d2/b
[ "`ls d`" = '' ] || exit 1
[ "`ls d2`" = 'b' ] || exit 1
# If dest exists and is a file, overwrite by default:
echo a > a
echo b > b
mv a b
[ "`ls`" = "b" ] || exit 1
[ "`cat b`" = "a" ] || exit 1
# If dest exists and is a dir, move into dir:
touch a
mkdir d
mv a d
## dirs
# Same as files except does not overwrite non empty dirs:
mkdir d
mkdir d2
mkdir d2/d
mv d d2
#d2/d was overwritten:
[ "`ls`" = "d2" ] || exit 1
[ "`ls d2`" = "d" ] || exit 1
mkdir d
touch d2/d/a
mv d d2
#cannot mv: dir not empty
## GNU extensions
## b ##s
# Make backup if dest exits
#if backupt exists, it is lost:
touch a
touch b
# Backup `a~` is made:
mv -b b a
[ -f a ] || exit 1
[ -f a~ ] || exit 1
[ `ls | wc -l` = 2 ] || exit 1
# Backup is only made if destination exists:
mv -b a b
[ -f a~ ] || exit 1
[ -f b ] || exit 1
[ `ls | wc -l` = 2 ] || exit 1
# If backup exists, it gets overwritten:
touch a
mv -b a b
[ -f a ] || exit 1
[ -f a~ ] || exit 1
[ `ls | wc -l` = 2 ] || exit 1
# Custom backup suffix:
touch a b
mv -bS ".bak" b a
[ -f a ] || exit 1
[ -f a.bak ] || exit 1
## rm
# Remove files and dirs.
# -r: recursive. Mandatory for directories. Potentially dangerous.
## rename
# Mass file regex renaming.
# Dry run:
rename -n 's/^([0-9]) /0$1 /g' *.mp3
# Act:
rename 's/^([0-9]) /0$1 /g' *.mp3
## install
# Move and set: mode, ownership and groups.
# Make all components of path:
install -d a/b/c
[ -d a ] || exit 1
[ -d a/b ] || exit 1
[ -d a/b/c ] || exit 1
## mkfifo
# POSIX 7
# Make a fifo (named pipe).
# Example:
mkfifo f
echo a > f &
# `echo` writes to the pipe with a write system call.
# The pipe has not been opened to read
# therefore the echo write system call blocks.
cat f
# Outputs `a`. Both `echo` and `cat` finish.
# - `cat` reads the pipe to read
# - `echo` puts its data on the pipe
# - `echo` terminates
# - `cat` reads the data from the pipe and terminates
## setterm
# Outputs stdout that changes terminal properties.
# Turns the cursor on/off:
setterm -cursor off
setterm -cursor on
## Users and groups
# To play around with those in Ubuntu, do ctrl+alt+f2, f3 ... f7
# and you will go into login shells
# so you can log with different users at the same time.
# List users:
cat /etc/passwd | sort
# Sample output:
#ciro:x:1000:1000:ciro,,,:/home/ciro:/bin/bash
# - `ciro`: user name
# - `x`: password is encrypted and stored in /etc/shadow
# - `1000`: user id. 0: root. 1-99: predefined. 100-999: reserved by system. 1000: first `normal` user
# - `1000`: primary user group
# - `ciro,,,` : comment field. Used by finger command.
# - `/home/ciro`: home dir
# - `/bin/bash`: login shell
# You are likely to see many users beside those which have a home directory.
# This is so because many applications create their own users.
# List groups:
cat /etc/group
# Format:
#groupname:x:5:user1,user2,user3
#x: encrypted pass if any
#5: group id. `regular` groups start at 1000
# Cat line of /etc/group for group g
getent group "$g"
cat /etc/default/useradd
## groups
# List groups of user `"$u"`:
groups "$u"
# Sample output:
username : group0 group1 group2
# List groups of the current user:
groups
## who
# POSIX 7.
# List who is logged on system.
who
## whoami
# Print effective user name:
whoami
# Same as `id -un`, but not POSIX, so never rely on it.
## last
# List last user logins on system:
last
## getty
# The tty that runs on those ctrl-alt-F\d things:
cat /etc/default/console-setup
# Allow you to change the number of consoles and their locations:
ACTIVE_CONSOLES="/dev/tty[1-6]"
## logout
# Logs out.
# Can only be used on the login shell.
logout
## faillog
# See log of failed login attempts (3 in a row):
faillog -a
## useradd
# Create a new user with username `$u`:
u=
sudo useradd -ms /bin/bash $u
sudo passwd "$u"
# For users that represent human end users, you will amost always want to use the following:
# - `-m` make home dir owned the user him with permissions 707.
# Without `-m` it is possible that X11 won't work.
# A tty login starts at `/`.
# Initial home dir files will me copied from a default template located at `/etc/skel`
# To change this template use: `-k /path/to/skel/`.
# Ro create no files: `-k /dev/null`
# If you forgot to use `-m` when you created the user this can be corrected by doing:
sudo mkdir /home/$u
sudo chmod 700 /home/$u $u
sudo chown /home/$u $u
# - `-p pass`
# Set password for the user.
# It is possible to create an user without a password,
# but then he won't be able to login.
# This has the disadvantage that the password will be visible.
# To create a password without showing it on screen,
# consider using the `passwd` command.
# - `-s` sets login shell
# You should probably set this to `/bin/bash`.
# If you forgot this, consider using chsh.
# - `-g 1001`: set group the user belongs to
# If g missing, either create a group u and add user
# to a default group specified in some config file
# - `-G 1002, 1003`: set secondary groups
# - `-c '$fullname,$office,$office2,$homephone'`
# Comment field thatwill end up on `/etc/passwd`.
# Any string is possiblt, but this particular format is recognized by the `finger` command
# and should always be used.
# To change this afterwards consier the `chfn` command.
# - `e`: password expires automatically at the given date.
# - `f`: account disables 5 days after password expires if pass not changed.
sudo useradd -e 2000-00-00 -f 5 $u
## userdel
# Remove users.
# Cannot be used on users current logged in.
# Delete user but keep his home directory:
userdel $u
# Also remove home directory:
userdel -r $u
## groupadd
# Create new groups
g=
sudo groupadd $g
## passwd
# File that holds usernames and key account options,
# and command line utility to edit that file.
# Actual passwords are normally stored hashed in the `/etc/shadow` file.
# Modify passwd for cur user:
passwd
# Modify passwd for user u:
sudo passwd "$u"
# If you are not u, you need sudo.
# Delete passwd for u, disabling login on his account:
sudo passwd -d "$u"
# Delete passwd for u, disabling login on his account
# until a new passwd is created.
# Lock account of user:
sudo passwd -l "$u"
# He cannot login anymore.
# `sudo su` and ssh public key based logins still work since they don't use the user's password.
# `sudo -u $u` also works.
# On the `/etc/shadow` file, an exclamation mark was added
# before hash of the password:
sudo cat /etc/shadow
# Before:
a:$6$hV0fIGJX$DHzAx0UJOJv9QFn5jW9dwIViqd3uuG86svgwy4JGh0tQz4oZwxoXpYw9sF1LGxePYHMI0nhxh.m3yIb8fy1p3/:16052:0:99999:7:::
# After:
a:!$6$hV0fIGJX$DHzAx0UJOJv9QFn5jW9dwIViqd3uuG86svgwy4JGh0tQz4oZwxoXpYw9sF1LGxePYHMI0nhxh.m3yIb8fy1p3/:16052:0:99999:7:::
# Unlock account:
sudo passwd -u "$u"
## vipw
# To directly edit the `/etc/passwd` file, use `vipw`,
# which is vi in a mode that checks the file syntax before saving,
# since syntax errors could lead to serious security faults.
## makepasswd
# Generates random passwords that follows certain rules.
# Useful to automate program installation when a password is required,
# for example on development servers.
# Make a 10 character password only with alhpanum chars:
makepasswd --chars 10
## chsh
# Change the default shell of current user to `/bin/bash`:
chsh -s /bin/bash
# View available shells on the system:
cat /etc/shells
## ac
# Register and view user login statistics.
# Current user connection in hours, broken by days:
ac -d
# Connection time for all users:
ac -p
## finger
# Shows user info.
# Data taken from a properly formated `/etc/passwd` comment field for the user.