-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathBash quick start guide=Tom Ryder;Note=Erxin.txt
2119 lines (1450 loc) · 61.4 KB
/
Bash quick start guide=Tom Ryder;Note=Erxin.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
Bash quick start guide=Tom Ryder;Note=Erxin
# Introduction
- reference
https://learning.oreilly.com/library/view/bash-quick-start/9781789538830/
- example code
https://github.com/PacktPublishing/Bash-Quick-Start-Guide
- what is bash
Bash is not (necessarily) part of Linux. They are separate pieces of software
Bash is not the same thing as SSH. SSH is a service and network protocol for running commands on remote computer
Bash is also not your terminal or TTY. Your terminal is a device for sending information to, and receiving information from, a computer.
Bash is not the same thing as PuTTY, iTerm, or xterm. These are terminal emulators
Bash is not the command line, in the strictest sense. Bash has an interactive mode
- getting bash
The Bash source code is available at https://www.gnu.org/software/bash/.
- check bash is running
$ declare -p BASH
printing the value of the SHELL variable:
$ echo "$SHELL"
- swtiching the login shell to bash
$ bash
find the location of the bash program:
```
bash$ declare -p BASH
BASH="/usr/local/bin/bash"
```
change Bash to your login shell to that path with the chsh tool:
$ chsh -s /usr/local/bin/bash
+ if get error "/usr/local/bin/bash is an invalid shell"
In this case, the invalid shell part likely means that the path given needs to be added to the /etc/shells file
$ cat /etc/shells
- identifyinng the bash version number
printing the value of the BASH_VERSION variable:
```
bash$ declare -p BASH_VERSION
declare -- BASH_VERSION="4.4.12(1)-release"
```
$ bash --version
- upgrading bash on macOS
$ brew install bash
- posix shell script features
http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
running command
variables
arithmetic expansion
control structure
aliases
functions
input and output redirection
pipes
argument list
parameter expansion
pattern matching
process management
compound commands
reading lines of input data
formatted strings
command substitution
+ calling the grep program, for example, you can select input lines using regular expressions
- bash specific features
named array variables
performing conditional tests
extended globs
regular expression
local varaibles
c-style loop
parameter expansion
arithmetic expression
irregular filenames and unusual line separators
- when to apply bash
prototyping
interactive system administration
automation
connecting programs together
filtering and transforming text input
navigating the unix file system
basic pattern matching on strings
portability to unix like systems
- when to avoid bash
speed requiring
fixed or floating point math
long or complex program
serialization
networking programming
object oriented programming
functional programming
concurrent programming
- getting help
$ help printf
$ man printf
+ the same command can have more than one implementation. In Bash, see a list with type command
$ type -a printf
+ try help first, example ubuntu output
```
$ help
GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu)
These shell commands are defined internally. Type `help' to see this list.
Type `help name' to find out more about the function `name'.
Use `info bash' to find out more about the shell in general.
Use `man -k' or `info' to find out more about commands not in this list.
A star (*) next to a name means that the command is disabled.
job_spec [&] history [-c] [-d offset] [n] or history -anrw [filename] or history >
(( expression )) if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ e>
. filename [arguments] jobs [-lnprs] [jobspec ...] or jobs -x command [args]
: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill ->
[ arg... ] let arg [arg ...]
[[ expression ]] local [option] name[=value] ...
alias [-p] [name[=value] ... ] logout [n]
bg [job_spec ...] mapfile [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [->
bind [-lpsvPSVX] [-m keymap] [-f filename] [-q name] [-u name] [-r ke> popd [-n] [+N | -N]
break [n] printf [-v var] format [arguments]
builtin [shell-builtin [arg ...]] pushd [-n] [+N | -N | dir]
caller [expr] pwd [-LP]
case WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esac read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] >
cd [-L|[-P [-e]] [-@]] [dir] readarray [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] >
command [-pVv] command [arg ...] readonly [-aAf] [name[=value] ...] or readonly -p
compgen [-abcdefgjksuv] [-o option] [-A action] [-G globpat] [-W word> return [n]
complete [-abcdefgjksuv] [-pr] [-DEI] [-o option] [-A action] [-G glo> select NAME [in WORDS ... ;] do COMMANDS; done
compopt [-o|+o option] [-DEI] [name ...] set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]
continue [n] shift [n]
coproc [NAME] command [redirections] shopt [-pqsu] [-o] [optname ...]
declare [-aAfFgilnrtux] [-p] [name[=value] ...] source filename [arguments]
dirs [-clpv] [+N] [-N] suspend [-f]
disown [-h] [-ar] [jobspec ... | pid ...] test [expr]
echo [-neE] [arg ...] time [-p] pipeline
enable [-a] [-dnps] [-f filename] [name ...] times
eval [arg ...] trap [-lp] [[arg] signal_spec ...]
exec [-cl] [-a name] [command [arguments ...]] [redirection ...] true
exit [n] type [-afptP] name [name ...]
export [-fn] [name[=value] ...] or export -p typeset [-aAfFgilnrtux] [-p] name[=value] ...
false ulimit [-SHabcdefiklmnpqrstuvxPT] [limit]
fc [-e ename] [-lnr] [first] [last] or fc -s [pat=rep] [command] umask [-p] [-S] [mode]
fg [job_spec] unalias [-a] name [name ...]
for NAME [in WORDS ... ] ; do COMMANDS; done unset [-f] [-v] [-n] [name ...]
for (( exp1; exp2; exp3 )); do COMMANDS; done until COMMANDS; do COMMANDS; done
function name { COMMANDS ; } or name () { COMMANDS ; } variables - Names and meanings of some shell variables
getopts optstring name [arg] wait [-fn] [id ...]
hash [-lr] [-p pathname] [-dt] [name ...] while COMMANDS; do COMMANDS; done
help [-dms] [pattern ...] { COMMANDS ; }
```
# Using bash interactively
- bash manual and gnu readline manual
```
$ man bash
$ man 3 readline
```
- simple command example
$ mkdir -p New/bash
- shell metacaracters have special meeting to bash
many other characters interpreted specially by Bash in some contexts, including {, [, *, and $ etc.
- quoting, Quoting special characters makes Bash ignore any special meaning they may otherwise have to the shell
- escaping, Using escaping with backslashes, the examples from the previous section
```
$ touch important\ files
$ touch Testfile\<Tom\>.doc
$ touch Review\;Final.doc
$ touch \$\$\$Money.doc
$ echo \\backslash\\
\backslash\
//can't escape newline within a word
$ echo backslash\
> foo\
> bar
backslashfoobar
```
- single quotes, single quotes can escape a newline in a word
$ echo 'quotes
> foo
> bar'
quotes
foo
bar
two single-quoted strings, It and s today, and pushes them together as one word. The way to do it is to use a backslash outside of the single quote
```
$ echo 'It'\''s today'
It's today
```
- double quote, they perform certain kinds of expansion within them, for shell variables and substitutions
```
$ echo "This is my login shell: $SHELL"
This is my login shell: /bin/bash
```
```
$ echo 'This is my login shell: $SHELL'
This is my login shell: $SHELL
```
+ include a literal dollar sign or backslash in a string by escaping it
```
$ echo "Not a variable: \$total"
Not a variable: $total
$ echo "Back\\to\\back\\slashes"
Back\to\back\slashes
```
backtick character is requried to be escaped
```
$ echo "Backticks: \`\`\`"
Backticks: ```
```
- quote concatenation, put different types of quoting together in the same word, as long as they can never separated by an unquoted space
```
$ echo Hello,\ "$USER"'! Welcome to '"$HOSTNAME"'!'
Hello, bashuser! Welcome to bashdemo!
```
- running commands in sequence
$ cd ; ls -a ; mkdir New
if one of the commands fails, Bash will still keep running the next command.
- exit values
$ rmdir ~/nonexistent
check the exist value $?
$ echo $?
- stopping a command list on error
$ cd && rmdir ~/nonexistent && ls
- running command in background with trail &
$ sleep 10 &
# Essential commands
- distinguishing command types
shell builtin commands, they are implemented in the bash binary itself like echo, type and source
runtime commands, defined at runtime during a Bash session, often by reading startup files
system commands, commands that can also be run outside of Bash. Examples are grep, ping, and rm.
- builtin commands:
type: Finding what a command is
echo: Printing arguments
printf: Printing formatted arguments
pwd: Printing the current directory
cd: Changing the current directory
set: Viewing and setting shell properties
declare: Managing variables and functions
test, [, [[: Evaluating expressions
- system commands, which are not part of Bash itself:
ls: Listing files for users
mv: Moving and renaming files
cp: Copying files
rm and rmdir: Deleting files and directories
grep: Matching patterns
cut: Extracting columns from data
wc: Counting lines, words, and characters
find: Iterating through a file tree
sort and uniq: Sorting and de-duplicating input
- get help for a command
$ help type
The type command, given the name of any command or commands
$ help type
/bin/true path was returned, even though true is also the name of a shell builtin.
- echo command, emit content to the terminal including variables
$ echo 'Hello, '"$USER"\!
Hello, bashuser!
- printf, where echo might struggle, the first argument you provide to it is a format string:
$ printf '%s\n' -n
-n
$ string=-n
$ printf '%s\n' "$string"
-n
- pwd, The pwd Bash builtin prints the current working directory
- tilde paths ~, reference the user home
$ echo ~
$ echo~root/.ssh
/root/.ssh
escape, single-quoting, and double-quoting all work to display ~ instead of reference the home path
$ echo \~bashuser
~bashuser
- cd command, ch to sets the working directory
$ cd <path>
- set command, set shell options, and set shell positional parameters.
set prints a list of all of the variables and any functions for the running shell, in alphabetical order. We suggest you use declare instead
set options
```
$ help set
-e: Exit immediately if a command exits with a non-zero status.
-n: Read commands but don't execute them. This is a useful way to check that your Bash script is syntactically correct
-v: Print shell input lines as they are read. This can be good for debugging
-x: Print commands and their arguments as they are executed.
```
set -x in the shell has the same effect as starting the shell as bash -x, or having a script's shebang line include the option, such as #!/bin/bash -x.
set followed by the option terminator string, --, can be used to set the positional parameters for the shell.
- declare command, only the -p option, declare prints the values of all of the variables in the current shell environment
```
bash$ declare -p
declare -- BASH="/bin/bash"
declare -r BASHOPTS="cdspell:checkhash:checkjobs:checkwinsize:...
declare -ir BASHPID
bash$ declare -p BASH PWD
declare -- BASH="/bin/bash"
declare -x PWD="/home/bashuser"
```
- test, [, and [[ commands
test file exist
$ test -e /etc/passwd && echo 'Password file exists!'
alternative way to write this command, called [
$ type -a [
$ [ -e /etc/passwd ] && echo 'Password file exists!'
Bash implements a new version of [ called [[. It's actually not really a command;
$ type [[
[[ keyword that in turn derives its syntax from the [ command.
- system commands
+ ls command
$ ls -al
+ getting filenames lists
use globs or find in this situation. If you only have to deal with one directory, use globs, as the commands tend to be simpler:
$ grep pattern -- *
$ find . -type f -exec grep pattern -- {} \;
- mv command, The mv command moves files or directories to a new directory
last argument is a directory, all of the arguments before it are moved into it
$ mv file1 file2 dir1 path/to/directory
- cp command, used to copy a file or set of files
$ cp file1 file2 file3 dir
copy a directory and all of the files beneath it:
$ cp -R olddir newdir
- rm and rmdir commands
You can force this with the standard -R or -r option, but it's safer to use rmdir. This is because rmdir will refuse to delete a directory if it still has files in it;
```
$ mkdir test1 test2
$ touch test1/file test2/file
$ rm -r test1
$ rmdir test2
rmdir: failed to remove 'test2': Directory not empty
```
- grep command match regular expression
$ grep 'telnet' /etc/services
$ grep '^telnet' /etc/services
$ grep -c telnet /etc/services
```
Usage: grep [OPTION]... PATTERNS [FILE]...
Search for PATTERNS in each FILE.
Example: grep -i 'hello world' menu.h main.c
PATTERNS can contain multiple patterns separated by newlines.
Pattern selection and interpretation:
-E, --extended-regexp PATTERNS are extended regular expressions
-F, --fixed-strings PATTERNS are strings
-G, --basic-regexp PATTERNS are basic regular expressions
-P, --perl-regexp PATTERNS are Perl regular expressions
-e, --regexp=PATTERNS use PATTERNS for matching
-f, --file=FILE take PATTERNS from FILE
-i, --ignore-case ignore case distinctions in patterns and data
--no-ignore-case do not ignore case distinctions (default)
-w, --word-regexp match only whole words
-x, --line-regexp match only whole lines
-z, --null-data a data line ends in 0 byte, not newline
Miscellaneous:
-s, --no-messages suppress error messages
-v, --invert-match select non-matching lines
-V, --version display version information and exit
--help display this help text and exit
Output control:
-m, --max-count=NUM stop after NUM selected lines
-b, --byte-offset print the byte offset with output lines
-n, --line-number print line number with output lines
--line-buffered flush output on every line
-H, --with-filename print file name with output lines
-h, --no-filename suppress the file name prefix on output
--label=LABEL use LABEL as the standard input file name prefix
-o, --only-matching show only nonempty parts of lines that match
-q, --quiet, --silent suppress all normal output
--binary-files=TYPE assume that binary files are TYPE;
TYPE is 'binary', 'text', or 'without-match'
-a, --text equivalent to --binary-files=text
-I equivalent to --binary-files=without-match
-d, --directories=ACTION how to handle directories;
ACTION is 'read', 'recurse', or 'skip'
-D, --devices=ACTION how to handle devices, FIFOs and sockets;
ACTION is 'read' or 'skip'
-r, --recursive like --directories=recurse
-R, --dereference-recursive likewise, but follow all symlinks
--include=GLOB search only files that match GLOB (a file pattern)
--exclude=GLOB skip files that match GLOB
--exclude-from=FILE skip files that match any file pattern from FILE
--exclude-dir=GLOB skip directories that match GLOB
-L, --files-without-match print only names of FILEs with no selected lines
-l, --files-with-matches print only names of FILEs with selected lines
-c, --count print only a count of selected lines per FILE
-T, --initial-tab make tabs line up (if needed)
-Z, --null print 0 byte after FILE name
Context control:
-B, --before-context=NUM print NUM lines of leading context
-A, --after-context=NUM print NUM lines of trailing context
-C, --context=NUM print NUM lines of output context
-NUM same as --context=NUM
--color[=WHEN],
--colour[=WHEN] use markers to highlight the matching strings;
WHEN is 'always', 'never', or 'auto'
-U, --binary do not strip CR characters at EOL (MSDOS/Windows)
When FILE is '-', read standard input. With no FILE, read '.' if
recursive, '-' otherwise. With fewer than two FILEs, assume -h.
Exit status is 0 if any line (or file if -L) is selected, 1 otherwise;
if any error occurs and -q is not given, the exit status is 2.
```
- cut command, select single columns of data from input separated by a single character
the -d specifies the delimiter or separator variable, in this case a colon, and -f specifies the number of the field (or column), starting from 1
$ cut -d: -f1,6 /etc/passwd
- wc, word count command, counts lines, words, and bytes of its input
$ wc .bashrc
more than one files
$ wc -c .bashrc .bash_profile
unicode 8 languages
$ wc -m -c japanese
6 16 japanese
the number of characters (6) is different from the number of bytes (16), as some of the characters are composed of more than one byte in UTF-8
- du command, getting file sizes with wc or du
The du program can show this information for a file or a directory, but its only portable unit size
- find command, operate recursively on a directory hierarchy
print filenames
$ find ~/recipes
explicit with the -print action:
$ find ~/recipes -print
the -name with this glob-style pattern will print the name of any file or directory
To find files modified more than three days ago, you could write:
$ find ~/recipes -mtime +3 -print
can do this with the -prune action, which stops the descent at that point and continues with the rest of the tree
```
Usage: find [-H] [-L] [-P] [`level] [-D debugopts] [path...] [expression]
default path is the current directory; default expression is -print
expression may consist of: operators, options, tests, and actions:
operators (decreasing precedence; -and is implicit where no others are given):
( EXPR ) ! EXPR -not EXPR EXPR1 -a EXPR2 EXPR1 -and EXPR2
EXPR1 -o EXPR2 EXPR1 -or EXPR2 EXPR1 , EXPR2
positional options (always true): -daystart -follow -regextype
normal options (always true, specified before other expressions):
-depth --help -maxdepth LEVELS -mindepth LEVELS -mount -noleaf
--version -xdev -ignore_readdir_race -noignore_readdir_race
tests (N can be +N or -N or N): -amin N -anewer FILE -atime N -cmin N
-cnewer FILE -ctime N -empty -false -fstype TYPE -gid N -group NAME
-ilname PATTERN -iname PATTERN -inum N -iwholename PATTERN -iregex PATTERN
-links N -lname PATTERN -mmin N -mtime N -name PATTERN -newer FILE
-nouser -nogroup -path PATTERN -perm [-/]MODE -regex PATTERN
-readable -writable -executable
-wholename PATTERN -size N[bcwkMG] -true -type [bcdpflsD] -uid N
-used N -user NAME -xtype [bcdpfls] -context CONTEXT
actions: -delete -print0 -printf FORMAT -fprintf FILE FORMAT -print
-fprint0 FILE -fprint FILE -ls -fls FILE -prune -quit
-exec COMMAND ; -exec COMMAND {} + -ok COMMAND ;
-execdir COMMAND ; -execdir COMMAND {} + -okdir COMMAND ;
Valid arguments for -D:
exec, opt, rates, search, stat, time, tree, all, help
Use '-D help' for a description of the options, or see find(1)
Please see also the documentation at http://www.gnu.org/software/findutils/.
```
+ executing commands for each result
search string in all files with names ending in .vim in a directory named vim:
$ find vim -type f -name '*.vim' -exec grep -F search -- {} \;
an option terminator (--), and two special arguments:
{}: Replaced with each find result
\;: Terminates the command
+ find and xargs to accomplish something similar to the -exec action of find:
$ find vim -type f -name '*.vim' | xargs grep -F search --
xargs is with the non-standard find -print0 and xargs -0 options that specify null-byte terminators between each file
$ find vim -type f -name '*.vim' -print0 | xargs -0 grep -F search --
- sort and uniq commands
two forms are the most useful:
$ sort /etc/shells
sort can sort data according to a particular column of its input data
$ sort -t: -k6,6 /etc/passwd
```
Usage: sort [OPTION]... [FILE]...
or: sort [OPTION]... --files0-from=F
Write sorted concatenation of all FILE(s) to standard output.
With no FILE, or when FILE is -, read standard input.
Mandatory arguments to long options are mandatory for short options too.
Ordering options:
-b, --ignore-leading-blanks ignore leading blanks
-d, --dictionary-order consider only blanks and alphanumeric characters
-f, --ignore-case fold lower case to upper case characters
-g, --general-numeric-sort compare according to general numerical value
-i, --ignore-nonprinting consider only printable characters
-M, --month-sort compare (unknown) < 'JAN' < ... < 'DEC'
-h, --human-numeric-sort compare human readable numbers (e.g., 2K 1G)
-n, --numeric-sort compare according to string numerical value
-R, --random-sort shuffle, but group identical keys. See shuf(1)
--random-source=FILE get random bytes from FILE
-r, --reverse reverse the result of comparisons
--sort=WORD sort according to WORD:
general-numeric -g, human-numeric -h, month -M,
numeric -n, random -R, version -V
-V, --version-sort natural sort of (version) numbers within text
Other options:
--batch-size=NMERGE merge at most NMERGE inputs at once;
for more use temp files
-c, --check, --check=diagnose-first check for sorted input; do not sort
-C, --check=quiet, --check=silent like -c, but do not report first bad line
--compress-program=PROG compress temporaries with PROG;
decompress them with PROG -d
--debug annotate the part of the line used to sort,
and warn about questionable usage to stderr
--files0-from=F read input from the files specified by
NUL-terminated names in file F;
If F is - then read names from standard input
-k, --key=KEYDEF sort via a key; KEYDEF gives location and type
-m, --merge merge already sorted files; do not sort
-o, --output=FILE write result to FILE instead of standard output
-s, --stable stabilize sort by disabling last-resort comparison
-S, --buffer-size=SIZE use SIZE for main memory buffer
-t, --field-separator=SEP use SEP instead of non-blank to blank transition
-T, --temporary-directory=DIR use DIR for temporaries, not $TMPDIR or /tmp;
multiple options specify multiple directories
--parallel=N change the number of sorts run concurrently to N
-u, --unique with -c, check for strict ordering;
without -c, output only the first of an equal run
-z, --zero-terminated line delimiter is NUL, not newline
--help display this help and exit
--version output version information and exit
KEYDEF is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where F is a
field number and C a character position in the field; both are origin 1, and
the stop position defaults to the line's end.
```
# Input, Output and Redirection
- Bash's support for classic shell redirection, specifying a source or a destination
- data-filtering possibilities using the sed and AWK programming languages
```
$ printf 'Hello, terminal!\n'
$ printf 'Hello, file!\n' > myfile
```
HOME can also be expanded for the file destination:
$ printf 'Hello, file!\n' > "$HOME"/myfile
+ only want to allow Bash to create new files, you can set the -C shell option with set:
$ set -C
$ printf 'Third command\n' > myfile
+ overwrite anyway
$ set -C
$ printf 'Third command\n' >| myfile
- appending to files
$ printf 'Second command\n' >> file
- created file permissions
create a new file using an output redirection, and examine it with ls -l:
$ printf 'Hello, world\n' > myfile
$ ls -l myfile -rw-r--r-- 1 bashuser bash
first field is file type, normal file is -, directory is d
next three rw- are the file owner permissions
next three r-- are the file group permission, a user in the file group
last three are the permission for the world
a numeric notation with three octal numbers ranging from 0 to 7:
$ stat -c %a myfile
read and write privileges, so the first value is 4 + 2, or 6
delete is 1
- choosing permissions for created files
umask value of the process to find out which of those permissions it should not apply to the created file
other three digits like so:
0022, is a common value for users who are not root. Note the extra zero at the start, a common prefix to signal an octal numbe
an "empty" umask of 0000, Bash creates new files that are readable and writable for everyone:
$ unmask
$ cat public-content > public
- redirecting errors
standard error strea's file descriptor number, which is always 2:
$ grep pattern myfile /nonexistent > matches 2> errors
Also note that you can use 2>> to append error output to a file
using the ampersand (&), syntax to specify 1 (the standard output stream's descriptor):
$ grep pattern myfile /nonexistent > matches 2>&1
- comm tool, which shows lines that differ between files, similar to diff
$ comm myfile1 myfile2 2> /dev/null
$ echo $?
1
- tee command, sending output to more than one place
$ printf 'Copy this output\n' | tee myfile
$ printf 'Copy this output\n' | tee myfile1 myfile2 myfile3
- redirecting input
use Bash to redirect input as often as you need to redirect output, because well-designed Unix programs can usually change their input behavior by specifying filenames
+ tr Unix command is a simple way to translate characters in input to other characters
$ tr a-z A-Z
Hello, world!
HELLO, WORLD!
+ from pipe
$ cat mylines | tr a-z A-Z
+ from file
$ tr a-z A-Z < mylines
we can place the input redirection operator, <, elsewhere on the command line, including at the very start
$ < mylines tr a-z A-Z
+ perform simultaneously
$ tr a-z A-Z < mylines > mylines.capitalized 2> mylines.error
- using a long string as input with here documents
input to cat all lines that are between the <<'EOF' line and the next occurrence of the EOF token as the first word of a new line;
```
#!/bin/bash
case $1 in
-h|--help)
cat <<'EOF'
foo command help:
-h, --help: Show this help
-q, --quiet: Run without diagnostics
-v, --verbose: Add extra diagnostics
EOF
exit 0
;;
esac
```
- using pipes
uppercase letters to lowercase with tr, sorts them, and then prints a count of how often each word is used, sorted by frequency
```
#!/bin/bash
# Convert all capital letters in the input to lowercase
tr A-Z a-z > words.lowercase
# Sort all the lowercase words in order
sort words.lowercase > words.sorted
# Print counts of how many times each word occurs
uniq -c words.sorted > words.frequency
# Sort that list by frequency, descending
sort -k1,1nr words.frequency
```
tr A-Z a-z | sort | uniq -c | sort -k1,1nr
- adding file contents to a stream
$ cat myfile1 myfile2 myfile3 > myfiles.combined
We could combine them with one pipeline using the - representation for the standard input
- piping ouytput from multiple programs
a group command, which is delimited with curly brackets, { and }:
$ { date ; hostname ; } | tr a-z A-Z
- filtering programs
we'll look at the sed and AWK programming language interpreters, both of which are specified by POSIX
- sed stream editor
read stream, edit, and send the result to output
delete individual lines with the d command, by prefixing them with the line number
$ sed '1d' text-file
substitutes a regular expression pattern into a given replacement:
$ sed 's/stream/river/' manual
```
Usage: sed [OPTION]... {script-only-if-no-other-script} [input-file]...
-n, --quiet, --silent
suppress automatic printing of pattern space
--debug
annotate program execution
-e script, --expression=script
add the script to the commands to be executed
-f script-file, --file=script-file
add the contents of script-file to the commands to be executed
--follow-symlinks
follow symlinks when processing in place
-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if SUFFIX supplied)
-l N, --line-length=N
specify the desired line-wrap length for the `l' command
--posix
disable all GNU extensions.
-E, -r, --regexp-extended
use extended regular expressions in the script
(for portability use POSIX -E).
-s, --separate
consider files as separate rather than as a single,
continuous long stream.
--sandbox
operate in sandbox mode (disable e/r/w commands).
-u, --unbuffered
load minimal amounts of data from the input files and flush
the output buffers more often
-z, --null-data
separate lines by NUL characters
--help display this help and exit
--version output version information and exit
If no -e, --expression, -f, or --file option is given, then the first
non-option argument is taken as the sed script to interpret. All
remaining arguments are names of input files; if no input files are
specified, then the standard input is read.
```
- awk programming language
AWK program is a set of patterns for each record (normally a line) to match, for which an action is performed for each matching record
$ awk '{ print $2 }' groceries
We can do this with a print command and by specifying the second column with $2
print multiple columns by separating them with commas:
$ awk '{ print $2, $3 }' groceries
NR in the preceding command refers to the record number
As with sed, these examples only scratch the surface; AWK is a small programming language
# Variables and patterns
- basic form of a variable
myshell='GNU Bourne-Again shell'
safest to quote all the values in their assignments; it might be unnecessary in some cases
```
myshell='sh'
myvar='GNU'\''s Not Unix!'
myprompt="$USER@$HOST"
```
- listing variables
$ today='August 9th'
$ printf '%s\n' "$today"
August 9th
$ declare -p today
list all
$ declare -p
- naming variables
all legal:
myvar