-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbash_tutorial.txt
1573 lines (748 loc) · 25.2 KB
/
bash_tutorial.txt
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
Tutorial
# Lesson 0 - Initial Info
# Lesson 1 - Navigation, files, folders
# Lesson 2 - Working with files
# Lesson 3 - Globs & regex
# Lesson 4 - Text processing
# Lesson 5 - Pipes & redirects, commands, command line, shortcuts, & prompts
# Lesson 6 - Ownership
# Lesson 7 - Jobs
# Lesson 8 - Network
# Lesson 9 - Read/write, variables, aliases, and functions
# Lesson 10 - Scripting
# Beyond! - Other stuff
More info at:
man bash
https://www.gnu.org/software/bash/manual/html_node/index.html
https://tldp.org/LDP/abs/html/
https://en.wikipedia.org/wiki/List_of_Unix_commands
# Lesson 0 - Initial Info
What's a shell?
What's bash?
What about other shells?
MacOS caveats
Also see: https://scriptingosx.com/2019/06/moving-to-zsh/
Commands can take --long-flags and/or -a abbreviations and/or parameters
## Self-Help
`man <command>`
manual entry for <command>
`man bash`
everything about the bash shell, built-ins, shortcuts, etc.
google/stackoverflow
`exit`
bail out
.-=-.
/ ! )\
__ \__/__/
/ _<( ^.^ )
/ / \ c /O
\ \_.-./=\.-._ _
`-._ `~` `-,./_<
`\' \'\`'----'
* \ . \ *
`-~~~\ .
. `-._`-._ *
* `~~~-, *
() * )
<^^> * ( .
.-""-. )
.---. ."-....-"-._ _...---''`/. '
( (`\ \ .' ``-'' _.-"'`
\ \ \ : :. .-'
`\`.\: `:. _.'
( .'`.` _.'
`` `-..______.-'
):. (
."-....-".
.':. `.
"-..______..-"
The exits are here, here, here, here, here, anywhere!
-Aladdin
# Lesson 1 - Navigation, files, folders
`pwd`
print working directory; where am I?
`cd`
change directory
`ls`
list contents of a directory
`rm`
remove
`mkdir`
make directory
`rmdir`
remove directory
`cp`
copy
`mv`
move (also rename)
~ or HOME
Both of these expand/substitute for something like this /home/<user>
# Lesson 2 - Working with files
## Files
File names are case sensitive
`.file`
This is a hidden file.
`foo\ bar`
A file named "foo bar" - spaces and other special characters are allowed, be careful with this
## Commands
`cat`
catenate - read text from file to output
`tac`
cat but lines will output in reverse order
`more`
pagenate
`less`
less is more, and then some
`touch`
update the timestamp on a file, creates an empty file if it doesn't exist
`mktemp`
create a temporary file for you to use
`tar`
tape archive - file splitting/merging/compression
`locate`
locate a file from a system db if it exists in the db after the last update occurred
`find`
find a file in real time
`basename`
trim a full path to just the name of the file
`diff`
compare files line by line to see what's different, output can be used by patch
`patch`
use the output of diff to apply changes to a file
`comm`
compare files to see what's similar
`head`
output the first lines of a file
`tail`
output the last lines of a file, you can tell it to keep giving you the last lines for logs
`tail -F`
Will keep your place outputting at the tail end of a file as it is written to.
# Lesson 3 - Globs & regex
## Unix globs
list any file with a name like this:
ls fil?{apple,b,e,4,82}*
?
exactly one character
*
0+ characters
{apple,b,e,4,82}
find any of apple, b, e, 4, 82 in that spot
## Regex
There are many flavors.
For consistancy, prefer javascript or PCRE (perl compatible regular expression).
Often like `/regex/` but you can use other characters `|regex|` or `{regex}`
For substitution `s/match/replace/` or `s{search}{replace}`
You can use modifiers like g & i after the last / (global and case-insensitive)
.
exactly one character
?
0-1 of the previous thing
`at?` will match a or at
*
0+ of the previous thing
`ar*` will match a or ar or arrrrrrrrrr
+
1+ of the previous thing
`ar+` will match ar or arr or arrrrrrr
[<stuff>]
a range of things to acceptable for this character
`gr[ae]y` will match gray or grey
`pa[a-zA-Z0-9_]*` will match password or pa5Sw0rd_1n_l337
[^<stuff>]
not this range of, but match anything else
Regex is a deep rabbit hole. Some complex examples...
`(\b[A-Z]+\b).*?\b(?=[a-z]+\b)(?i)\1(?# almost done)\b`
Test if an uppercase word exists elsewhere as a lowercase word (DOG and dog).
This uses ranges, special escape characters, groups,
back references, look arounds, inline modifiers, and comments.
```
(?(DEFINE) # start DEFINE block
# pre-define quant subroutine
(?<quant>many|some|five)
# pre-define adj subroutine
(?<adj>blue|large|interesting)
# pre-define object subroutine
(?<object>cars|elephants|problems)
# pre-define noun_phrase subroutine
(?<noun_phrase>(?&quant)\ (?&adj)\ (?&object))
# pre-define verb subroutine
(?<verb>borrow|solve|resemble)
) # end DEFINE block
##### The regex matching starts here #####
(?&noun_phrase)\ (?&verb)\ (?&noun_phrase)
```
will match phrases such as
"five blue elephants solve many interesting problems"
"many large problems resemble some interesting cars"
?
????? ??_??
????? ??????
???????$$
?????????$$$$$
??? ???$$$$$$
$$$$$$
$$$$$$$
$$$$$$$ ??????
$$$$$$$$??????????????
$$$$$$$$$?????????????
?????$$$$$$$$$????????????
?????????$$$$$$$$$???????????$
?????????????$$$$$$$$$$$???????$$$
???????????????$$$$$$$$$$$?????$$$
$?????????????????$$$$$££££££??????
$$$????????????????$??£££££££$$$$????? $
$$$$$??????????????????£££££££££$$$$?????????$
$$$$$$???????????$$$???£££££££££??$$??$$?????$$$
$$$$$$$$$$$????$?$???£££££££££££??$$$???????????$$
$$$$$$$$$$???$$???????££££££££??????????????????$
$ $$$???$$????????££$$$$$$??????????????????$
$$????$$???????$$$$$$$$??????????????????$
$$??$??$$?????????$$$$$$??????????????????$
????$$$$????????????$$$$$$????????????????$
$$$$?????????????????????$$$$??????????????$$
$$$$??????????????????????$$$$???????????$$$
$$$???????????????????????$$$$???????$$$$
$$????????????????????????$$$$$$??$$$$
$$$???????????????????????$$$$$$$$$
$$$$??????????????????????$$$$$$
$$$$$$$???????????????$$$$$$$
$$$$$$$$?????$$$$$$$$$$$
$$$$$$$$$$$$$$$$$
Matchmaker matchmaker make me a match.
-Fiddler on the Roof
# Lesson 4 - Text processing
`nano`, `vim`, `emacs`, `ed`
text editors
`wc`
word count, or lines, or characters
`sort`
sort things
`uniq`
unique, remove duplicates
`grep`
search for text in files
from the ed command, Globally (search) Regular Expression Print (g/re/p)
perl
Practical Extraction and Report Language
language designed for text processing - grep inside perl can be faster than grep
`jq`
Do stuff with json
`tr`
translate from one set of characters to another
`expand`
convert tabs to spaces
`cut`
get a piece out of a string or the same piece out of the lines of a file
`sed`
stream editor - s/search/replace/g
`awk`
(initials of 3 names) scripting language to deal with files of data
_,.---.---.---.--.._
_.-' `--.`---.`---'-. _,`--.._
/`--._ .'. `. `,`-.`-._\
|| \ `.`---.__`__..-`. ,'`-._/
_ ,`\ `-._\ \ `. `_.-`-._,``-.
,` `-_ \/ `-.`--.\ _\_.-'\__.-`-.`-._`.
(_.o> ,--. `._/'--.-`,--` \_.-' \`-._ \
`---' `._ `---._/__,----` `-. `-\
/_, , _..-' `-._\
\_, \/ ._(
\_, \/ ._\
`._,\/ ._\
`._// ./`-._
`-._-_-_.-'
Awkward turtle.
# Lesson 5 - Pipes & redirects, commands, command line, shortcuts, & prompts
Definitions:
blank space or tab
word aka token, sequence of characters considered as a single unit
name word consisting of only alphanumeric and underscore not starting with a number
metacharacter character that separates words when not quoted
control operator token that performs a control function, example ; ends a command
command - optional variable assignments followed by blank separated words & redirects,
terminated by a control operator
pipeline - one or more commands separated by by | or |& (shorthand for 2>&1 |)
lists - one or more pipelines separated by ;, &, &&, || (& - run in the background, not and)
Compound commands
(list) - executed in a subshell env variable assignments and builtin commands
that affect the env do not remain after the command completes.
{ list; } - list is executed in the current shell env.
You need spaces because braces aren't reserved words.
PATH
a system variable you can update to tell the os where to look for commands you run
## Pipes and redirection
Numbers are actually file descriptors in /dev/fd. /dev/null is like a black hole or garbage can.
+----------------+ 1. Standard Output
0. Standard Input | |---------------------->
--------------------->| Command | 2. Error Output
| |---------------------->
+----------------+
+--+
+----+--+---+
| /dev/null |
|------------
| | | | |
| | | | |
| | | | |
+-----------+
trashcan
`|`
A pipe
`>`, `>>`, `<`
Redirects
`&1`
A file descriptor when on the right of the redirect because it has an &, otherwise 1 is a file.
The left side of a redirect is always a file descriptor, no & needed.
cmd1 | cmd2 - pipe/connect the standard output from cmd1 into the standard input of cmd2
cmd 2>&1 - write error output into the standard output file descriptor
cmd >file - write standard output (default) to new file
cmd <file - read contents of file into the standard input for cmd
cmd 2>>file - append error output to file
n<&- - close input file descriptor n
m>&- - close output file descriptor m
cmd &>/dev/null - send all output to a black hole
## Commands
`tee`
like a plumber's T pipe. Read from standard input. Write to the specified file as well as stdout.
`which`
which is the full path of this command if I'm actually running that command
`type`
type of this command that I'm running when I execute this
`clear`
clear the terminal, also C-l (really just scrolls up)
`history`
history of commands
`!`
rerun command from history - !! rerun last command, there are lots of other options for ! as well
`tmux` (also `screen`)
If you are remoted in, lets you reconnect to your session if you are disconnected.
Also allows virtual desktops and split screens
## Command Substitution
`command` == $(command)
This is how you get the result of a command into a string or as a parameter to another command.
$(command) is preferred to `command`
You can nest substitutions easily and it is similar to variable substitutions which also use $.
## Shortcuts
`C-r`
reverse search through commands
`C-a`
start of line
`C-e`
end of line
`M-f`
forward word
`M-b`
back word
`C-M-e`
expand commands that I've typed - aliases, variables, etc.
`C-x *`
expand globs
`C-x g`
list the expansions
`C-_`
undo commandline changes
## Prompt Variables
PS0 - String displayed with prompt expansion just before executing a command via PS1 prompt
PS1 - Standard commandline prompt (default: \s-\v\$) (shell name-version$)
PS2 - If you have multiple lines of command, what to show on continuing lines (default: >)
PS3 - What to show if you use the `select` command in a script (default: #?)
PS4 - What to show during output tracing using `set -x` in a script (default: ++)
PROMPT_COMMAND - Execute contents of this before showing PS1, not prompt expanded.
Before expansion PROMPT_COMMAND was used to set the PS1 prompt before displaying it.
To capture timing:
```
PS0='\D{%I:%M:%S %P}\n'
PROMPT_COMMAND='date +"%I:%M:%S %P"'
```
Will cause this:
```
> sleep 10 && echo hello
03:03:39 pm
hello
03:03:49 pm
```
For better debugging, you can set PS4 inside a script
```
export PS4='Script[$0]:Line[$LINENO]:: '
set -x
echo "PS4 demo script"
> /bin/bash debug_helper.sh
Script[debug_helper.sh]:Line[3]:: echo 'PS4 debugging demo script'
PS4 debugging demo script
```
__...--~~~~~-._ _.-~~~~~--...__
// `V' \\
// | \\
//__...--~~~~~~-._ | _.-~~~~~~--...__\\
//__.....----~~~~._\ | /_.~~~~----.....__\\
====================\\|//====================
`---`
The most significant lesson of history is that we never learn from history.
Any good history book is mainly just a long list of mistakes complete with names and dates.
It's very embarrassing.
-A. Whitney Brown
# Lesson 6 - Ownership
`ls -l`
will show permissions
-rw-r--r-- file
drwxr-xr-x folder
^ ^ ^ ^
| | | |
| | | +-- read write execute for all users
| | +----- read write execute for group
| +-------- read write execute for user
+---------- directory?
`chmod`
change modifiers (permissions) - user/group/all
`chown`
change ownership
`stat`
shows file status ownership/permissions
`stat -c "%u:%g %U:%G" /app/`
`su`
substitute user OR super user - become another user
`sudo`
substitute user do - much more flexible than su; also, we know who you really are
.--------.
____/ \
|.--, |
||__| |
'---, |
|____________|
|\ \ \ \ \ \ |
| \ \ \ \ \ \|
|\ \ \ \ \ \ |
| \ \ \ \ \ \|
|\ \ \ \ \ \ |
| \ \ \ \ \ \|
|\ \ \ \ \ \ |
| \ \ \ \ \ \|
|\ \ \ \ \ \ |
| \ \ \ \ \ \|
|\ \ \ \ \ \ |
|_\_\_\_\_\_\|
`""""""""""""`
All I need is this thermos.
-The Jerk
# Lesson 7 - Jobs
`jobs`
list the running jobs (commands)
`fg`
foreground specified job
`bg`
background specified job
`C-c`
cancel job
`C-z`
halt job
`sleep`
wait for some amount of time
`ps`
list processes and their ids
`kill`
terminate a process by its process id with a signal
Signal Value Action Comment
SIGHUP 1 Term Hangup detected on controlling terminal or death of controlling process
SIGINT 2 Term Interrupt from keyboard
SIGQUIT 3 Core Quit from keyboard
SIGILL 4 Core Illegal Instruction
SIGABRT 6 Core Abort signal from abort
SIGFPE 8 Core Floating-point exception
SIGKILL 9 Term Kill signal
SIGSEGV 11 Core Invalid memory reference
SIGPIPE 13 Term Broken pipe: write to pipe with no readers;
SIGALRM 14 Term Timer signal from alarm
SIGTERM 15 Term Termination signal
SIGUSR1 30,10,16 Term User-defined signal 1
SIGUSR2 31,12,17 Term User-defined signal 2
SIGCHLD 20,17,18 Ign Child stopped or terminated
SIGCONT 19,18,25 Cont Continue if stopped
SIGSTOP 17,19,23 Stop Stop process
SIGTSTP 18,20,24 Stop Stop typed at terminal
SIGTTIN 21,21,26 Stop Terminal input for background process
SIGTTOU 22,22,27 Stop Terminal output for background process
`pkill`
kill using the process name instead of id
`trap`
do something when a signal is sent - example: confirm close without saving
`pgrep`
search processes by name
`pstree`
visualize processes in a tree to see parent/child relationships
`nice`
start a command with a different priority
`renice`
change a running command's priority
`cron`
command run on - task scheduling
`crontab`