-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbashgnu.sh
More file actions
4446 lines (3104 loc) · 169 KB
/
bashgnu.sh
File metadata and controls
4446 lines (3104 loc) · 169 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
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
# control operator: newline or
# ‘||’, ‘&&’, ‘&’, ‘;’, ‘;;’, ‘;&’, ‘;;&’, ‘|’, ‘|&’, ‘(’, or ‘)’.
sbhi command caller ko exit status
value return krTi h. zo 8bit hoTi h. isliy return valu maksimum 255 hoTi h.
field
A unit of text that is the result of one of the shell expansions. After expansion,
when executing a command, the resulting fields are used as the command name
and arguments.
filename A string of characters used to identify a file.
job
A set of processes comprising a pipeline, and any processes descended from it,
that are all in the same process group.
job control
A mechanism by which users can selectively stop (suspend) and restart (resume)
execution of processes.
metacharacter
A character that, when unquoted, separates words. A metacharacter is a space,
tab, newline, or one of the following characters: , , , , , , or .
process group
A collection of related processes each having the same process group id.
process group ID
A simple shell command such as echo a b c consists of the command itself followed by
arguments, separated by spaces.
More complex shell commands are composed of simple commands arranged together in
a variety of ways: in a pipeline in which the output of one command becomes the input of
a second, in a loop or conditional construct, or in some other grouping.
3.2.1 Reserved Words
Reserved words are words that have special meaning to the shell. They are used to begin
and end the shells just a sequence of
words separated by blanks, terminated by one of the shells arguments.
The return status (see Section 3.7.5 [Exit Status], page 44) of a simple command is its
exit status as provided by the posix 1003.1 waitpid function, or 128+n if the command
was terminated by signal n.
Chapter 3: Basic Shell Features
10
3.2.3 Pipelines
A pipeline is a sequence of one or more commands separated by one of the control operators
or .
The format for a pipeline is
[time [-p]] [!] command1 [ | or |& command2 ] ...
The output of each command in the pipeline is connected via a pipe to the input of the next
command. That is, each command reads the previous command|&s standard error, in addition to its standard output, is con-
nected to command2s execution. The -p option changes the output format to
that specified by posix. When the shell is in posix mode (see Section 6.11 [Bash POSIX
Mode], page 106), it does not recognize time as a reserved word if the next token begins
with a . The TIMEFORMAT variable may be set to a format string that specifies how the
timing information should be displayed. See Section 5.2 [Bash Variables], page 78, for a
description of the available formats. The use of time as a reserved word permits the timing
of shell builtins, shell functions, and pipelines. An external time command cannot time
these easily.
When the shell is in posix mode (see Section 6.11 [Bash POSIX Mode], page 106), time
may be followed by a newline. In this case, the shell displays the total user and system time
consumed by the shell and its children. The TIMEFORMAT variable may be used to specify
the format of the time information.
If the pipeline is not executed asynchronously (see Section 3.2.4 [Lists], page 10), the
shell waits for all commands in the pipeline to complete.
3.2.5.1 Looping Constructs
echo -n "Enter the name of an animal: "
read ANIMAL
echo -n "The $ANIMAL has "
case $ANIMAL in
horse | dog | cat) echo -n "four";;
man | kangaroo ) echo -n "two";;
*) echo -n "an unknown number of";;
esac
echo " legs."
select name [in words ...]; do commands; done
select
select fname in *;
do
echo you picked $fname \($REPLY\)
break;
done
(( expression ))
[[ expression ]]
[[ . =~ [.] ]]
The shell performs any word expansions before passing the pattern to the reg-
ular expression functions, so you can assume that the shells necessary.
The array variable BASH_REMATCH records which parts of the string matched
the pattern. The element of BASH_REMATCH with index 0 contains the portion
of the string matching the entire regular expression. Substrings matched by
parenthesized subexpressions within the regular expression are saved in the
remaining BASH_REMATCH indices. The element of BASH_REMATCH with index n
is the portion of the string matching the nth parenthesized subexpression.
Bash sets BASH_REMATCH in the global scope; declaring it as a local variable will
lead to unexpected results.
Expressions may be combined using the following operators, listed in decreasing
order of precedence:
( expression )
! expression
expression1 && expression2
expression1 || expression2
3.2.5.3 Grouping Commands
( list )
{ list; }
3.2.6 Coprocesses
coproc [NAME] command [redirections]
This creates a coprocess named NAME. command may be either a simple command (see
Section 3.2.2 [Simple Commands], page 9) or a compound command (see Section 3.2.5
If NAME is not
[Compound Commands], page 11). NAME is a shell variable name.
supplied, the default name is COPROC.
The recommended form to use for a coprocess is
coproc NAME { command; }
This form is recommended because simple commands result in the coprocess always being
named COPROC, and it is simpler to use and more complete than the other compound
commands.
There are other forms of coprocesses:
coproc NAME compound-command
coproc compound-command
coproc simple-command
If command is a compound command, NAME is optional. The word following coproc
determines whether that word is interpreted as a variable name: it is interpreted as NAME
if it is not a reserved word that introduces a compound command. If command is a simple
command, NAME is not allowed; this is to avoid confusion between NAME and the first
word of the simple command.
When the coprocess is executed, the shell creates an array variable (see Section 6.7
[Arrays], page 100) named NAME in the context of the executing shell. The standard
output of command is connected via a pipe to a file descriptor in the executing shell, and
that file descriptor is assigned to NAME[0]. The standard input of command is connected
via a pipe to a file descriptor in the executing shell, and that file descriptor is assigned
to NAME[1]. This pipe is established before any redirections specified by the command
(see Section 3.6 [Redirections], page 38). The file descriptors can be utilized as arguments
to shell commands and redirections using standard word expansions. Other than those
created to execute command and process substitutions, the file descriptors are not available
in subshells.
The process ID of the shell spawned to execute the coprocess is available as the value of
the variable NAME_PID. The wait builtin command may be used to wait for the coprocess
to terminate.
Chapter 3: Basic Shell Features
Since the coprocess is created as an asynchronous command, the coproc command always
returns success. The return status of a coprocess is the exit status of command.
3.2.7 GNU Parallel
There are ways to run commands in parallel that are not built into Bash. GNU Parallel is
a tool to do just that.
GNU Parallel, as its name suggests, can be used to build and run commands in parallel.
You may run the same command with different arguments, whether they are filenames,
usernames, hostnames, or lines read from files. GNU Parallel provides shorthand references
to many of the most common operations (input lines, various portions of the input line,
different ways to specify the input source, and so on). Parallel can replace xargs or feed
commands from its input sources to several different instances of Bash.
For a complete description, refer to the GNU Parallel documentation, which is available
at https://www.gnu.org/software/parallel/parallel_tutorial.html.
3.3 Shell Functions
Shell functions are a way to group commands for later execution using a single name for
the group. They are executed just like a "regular" command. When the name of a shell
function is used as a simple command name, the list of commands associated with that
function name is executed. Shell functions are executed in the current shell context; no new
process is created to interpret them.
Functions are declared using this syntax:
fname () compound-command [ redirections ]
or
function fname [()] compound-command [ redirections ]
This defines a shell function named fname. The reserved word function is optional.
If the function reserved word is supplied, the parentheses are optional. The body of the
function is the compound command compound-command (see Section 3.2.5 [Compound
Commands], page 11). That command is usually a list enclosed between { and }, but may
be any compound command listed above. If the function reserved word is used, but the
parentheses are not supplied, the braces are recommended. compound-command is executed
whenever fname is specified as the name of a simple command. When the shell is in posix
mode (see Section 6.11 [Bash POSIX Mode], page 106), fname must be a valid shell name
and may not be the same as one of the special builtins (see Section 4.4 [Special Builtins],
page 77). In default mode, a function name can be any unquoted shell word that does not
contain . Any redirections (see Section 3.6 [Redirections], page 38) associated with the
shell function are performed when the function is executed. A function definition may be
deleted using the -f option to the unset builtin (see Section 4.1 [Bourne Shell Builtins],
page 48).
The exit status of a function definition is zero unless a syntax error occurs or a readonly
function with the same name already exists. When executed, the exit status of a function
is the exit status of the last command executed in the body.
Note that for historical reasons, in the most common usage the curly braces that surround
the body of the function must be separated from the body by blanks or newlines. This
is because the braces are reserved words and are only recognized as such when they are
separated from the command list by whitespace or another shell metacharacter. Also, when
using the braces, the list must be terminated by a semicolon, a , or a newline.
When a function is executed, the arguments to the function become the positional pa-
rameters during its execution (see Section 3.4.1 [Positional Parameters], page 23). The
special parameter that expands to the number of positional parameters is updated to
reflect the change. Special parameter 0 is unchanged. The first element of the FUNCNAME
variable is set to the name of the function while the function is executing.
All other aspects of the shell execution environment are identical between a function and
its caller with these exceptions: the DEBUG and RETURN traps are not inherited unless the
function has been given the trace attribute using the declare builtin or the -o functrace
option has been enabled with the set builtin, (in which case all functions inherit the DEBUG
and RETURN traps), and the ERR trap is not inherited unless the -o errtrace shell option
has been enabled. See Section 4.1 [Bourne Shell Builtins], page 48, for the description of
the trap builtin.
The FUNCNEST variable, if set to a numeric value greater than 0, defines a maximum
function nesting level. Function invocations that exceed the limit cause the entire command
to abort.
If the builtin command return is executed in a function, the function completes and
execution resumes with the next command after the function call. Any command associated
with the RETURN trap is executed before execution resumes. When a function completes,
the values of the positional parameters and the special parameter are restored to the
values they had prior to the functions return status; otherwise the functions caller and so on, back to the "global" scope, where
the shell is not executing any shell function. Consequently, a local variable at the current
local scope is a variable declared using the local or declare builtins in the function that
is currently executing.
Local variables "shadow" variables with the same name declared at previous scopes.
For instance, a local variable declared in a function hides a global variable of the same
name: references and assignments refer to the local variable, leaving the global variable
unmodified. When the function returns, the global variable is once again visible.
The shell uses dynamic scoping to control a variablefunc1 local+=s previous value. This includes arguments to builtin commands
such as declare that accept assignment statements (declaration commands). When is
applied to a variable for which the integer attribute has been set, value is evaluated as
an arithmetic expression and added to the variable+=s value is not unset (as it is when using ), and new
values are appended to the array beginning at one greater than the arrays value.
A variable can be assigned the nameref attribute using the -n option to the declare or
local builtin commands (see Section 4.2 [Bash Builtins], page 55) to create a nameref, or a
reference to another variable. This allows variables to be manipulated indirectly. Whenever
the nameref variable is referenced, assigned to, unset, or has its attributes modified (other
than using or changing the nameref attribute itself), the operation is actually performed on
the variable specified by the nameref variables arguments when it is invoked,
and may be reassigned using the set builtin command. Positional parameter N may be
referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may
not be assigned to with assignment statements. The set and shift builtins are used to
set and unset them (see Chapter 4 [Shell Builtin Commands], page 48). The positional
parameters are temporarily replaced when a shell function is executed (see Section 3.3
[Shell Functions], page 19).
When a positional parameter consisting of more than a single digit is expanded, it must
be enclosed in braces.
3.4.2 Special Parameters
($*) Expands to the positional parameters, starting from one. When the ex-
($@) Expands to the positional parameters, starting from one.
($#) Expands to the number of positional parameters in decimal.
($?) Expands to the exit status of the most recently executed foreground
($-, a hyphen.) Expands to the current option flags as specified upon invocation,
($$) Expands to the process id of the shell. In a subshell, it expands to the
($!) Expands to the process id of the job most recently placed into the back-
($0) Expands to the name of the shell or shell script. This is set at shell
initialization. If Bash is invoked with a file of commands (see Section 3.8 [Shell
Scripts], page 46), $0 is set to the name of that file. If Bash is started with the
-c option (see Section 6.1 [Invoking Bash], page 91), then $0 is set to the first
argument after the string to be executed, if one is present. Otherwise, it is set
to the filename used to invoke Bash, as given by argument zero.
3.5 Shell Expansions
Expansion is performed on the command line after it has been split into tokens. There are
seven kinds of expansion performed:
tilde expansion
command substitution
word splitting
0,${}~~+~-+-+-+:=~-dirs +Ndirs +Ndirs -N$}:-s existence and that its value is not null; if the colon is omitted, the
operator tests only for existence.
${parameter:@*@*:-@*@*@@*@*@###@*@*%%%@*@*#%/&&&&&&& & t take any enclosing double
quotes into account.
Since backslash can escape , it can also escape a backslash in the replacement
string. This means that will insert a literal backslash into the replacement,
so these two echo commands
var=abcdef
rep=
echo ${var/abc/\\&xyz}
echo ${var/abc/$rep}
will both output .
It should rarely be necessary to enclose only string in double quotes.
If the nocasematch shell option (see the description of shopt in Section 4.3.2
[The Shopt Builtin], page 71) is enabled, the match is performed without regard
to the case of alphabetic characters. If parameter is or , the substitution
operation is applied to each positional parameter in turn, and the expansion is
the resultant list. If parameter is an array variable subscripted with or ,
the substitution operation is applied to each member of the array in turn, and
the expansion is the resultant list.
${parameter^pattern}
${parameter^^pattern}
${parameter,pattern}
${parameter,,pattern}
${parameter@operator}
U u L Q E P A K a k
3.5.5 Arithmetic Expansion
$(( expression ))
3.5.6 Process Substitution
Process substitution allows a process*?[......?........***/*s collating sequence and character
set, is matched. If the first character following the is a or a then any
character not enclosed is matched. A ][a-dx-z][abcdxyz][a-dx-z][abcdxyz][aBbCcDdxYyZz]C[]_[][]|.......\, and
that did not result from one of the above expansions are removed.
3.6 Redirections
Before a command is executed, its input and output may be redirected using a special no-
tation interpreted by the shell. Redirection allows commandss lifetime
manually. The varredir_close shell option manages this behavior (see Section 4.3.2 [The
Shopt Builtin], page 71).
In the following descriptions, if the file descriptor number is omitted, and the first char-
acter of the redirection operator is , the redirection refers to the standard input (file
descriptor 0). If the first character of the redirection operator is , the redirection refers
to the standard output (file descriptor 1).
The word following the redirection operator in the following descriptions, unless other-
wise noted, is subjected to brace expansion, tilde expansion, parameter expansion, command
substitution, arithmetic expansion, quote removal, filename expansion, and word splitting.
If it expands to more than one word, Bash reports an error.
Note that the order of redirections is significant. For example, the command
ls > dirlist 2>&1
directs both standard output (file descriptor 1) and standard error (file descriptor 2) to the
file dirlist, while the command
ls 2>&1 > dirlist
directs only the standard output to file dirlist, because the standard error was made a copy
of the standard output before the standard output was redirected to dirlist.
Bash handles several filenames specially when they are used in redirections, as described
in the following table. If the operating system on which Bash is running provides these
special files, bash will use them; otherwise it will emulate them internally with the behavior
described below.
/dev/fd/fd
If fd is a valid integer, file descriptor fd is duplicated.
/dev/stdin File descriptor 0 is duplicated.
/dev/stdout File descriptor 1 is duplicated.
/dev/stderr File descriptor 2 is duplicated.
/dev/tcp/host/port
If host is a valid hostname or Internet address, and port is an integer port
number or service name, Bash attempts to open the corresponding TCP socket.
/dev/udp/host/port
If host is a valid hostname or Internet address, and port is an integer port
number or service name, Bash attempts to open the corresponding UDP socket.
A failure to open or create a file causes the redirection to fail.
Redirections using file descriptors greater than 9 should be used with care, as they may
conflict with file descriptors the shell uses internally.
3.6.1 Redirecting Input
Redirection of input causes the file whose name results from the expansion of word to be
opened for reading on file descriptor n, or the standard input (file descriptor 0) if n is not
specified.
[n]<word
3.6.2 Redirecting Output
Redirection of output causes the file whose name results from the expansion of word to be
opened for writing on file descriptor n, or the standard output (file descriptor 1) if n is not
specified. If the file does not exist it is created; if it does exist it is truncated to zero size.
The general format for redirecting output is:
[n]>[|]word
If the redirection operator is , and the noclobber option to the set builtin has been
enabled, the redirection will fail if the file whose name results from the expansion of word
exists and is a regular file. If the redirection operator is , or the redirection operator is
and the noclobber option is not enabled, the redirection is attempted even if the file
named by word exists.
3.6.3 Appending Redirected Output
[n]>>word
3.6.4 Redirecting Standard Output and Standard Error
This construct allows both the standard output (file descriptor 1) and the standard error
output (file descriptor 2) to be redirected to the file whose name is the expansion of word.
&>word # same as >word 2>&1
When using the second form, word may not expand to a number or .
If it does,
other redirection operators apply (see Duplicating File Descriptors below) for compatibility
reasons.
3.6.5 Appending Standard Output and Standard Error
This construct allows both the standard output (file descriptor 1) and the standard error
output (file descriptor 2) to be appended to the file whose name is the expansion of word.
The format for appending standard output and standard error is:
&>>word # This is semantically equivalent to >>word 2>&1
(see Duplicating File Descriptors below).
3.6.6 Here Documents
This type of redirection instructs the shell to read input from the current source until a line
containing only word (with no trailing blanks) is seen. All of the lines read up to that point
are then used as the standard input (or file descriptor n if n is specified) for a command.
The format of here-documents is:
[n]<<[\\$.
If the redirection operator is , then all leading tab characters are stripped from input
lines and the line containing delimiter. This allows here-documents within shell scripts to
be indented in a natural fashion.
Chapter 3: Basic Shell Features
41
3.6.7 Here Strings
A variant of here documents, the format is:
[n]<<< word
The word undergoes tilde expansion, parameter and variable expansion, command sub-
stitution, arithmetic expansion, and quote removal. Filename expansion and word splitting
are not performed. The result is supplied as a single string, with a newline appended, to
the command on its standard input (or file descriptor n if n is specified).
3.6.8 Duplicating File Descriptors
The redirection operator
[n]<&word
is used to duplicate input file descriptors. If word expands to one or more digits, the file
descriptor denoted by n is made to be a copy of that file descriptor. If the digits in word
do not specify a file descriptor open for input, a redirection error occurs. If word evaluates
to , file descriptor n is closed. If n is not specified, the standard input (file descriptor 0)
is used.
The operator
[n]>&word
is used similarly to duplicate output file descriptors.
If n is not specified, the standard
output (file descriptor 1) is used. If the digits in word do not specify a file descriptor open
for output, a redirection error occurs. If word evaluates to , file descriptor n is closed.
As a special case, if n is omitted, and word does not expand to one or more digits or ,
the standard output and standard error are redirected as described previously.
3.6.9 Moving File Descriptors
The redirection operator
[n]<&digit-
moves the file descriptor digit to file descriptor n, or the standard input (file descriptor 0)
if n is not specified. digit is closed after being duplicated to n.
Similarly, the redirection operator
[n]>&digit-
moves the file descriptor digit to file descriptor n, or the standard output (file descriptor 1)
if n is not specified.
3.6.10 Opening File Descriptors for Reading and Writing
The redirection operator
[n]<>word
causes the file whose name is the expansion of word to be opened for both reading and
writing on file descriptor n, or on file descriptor 0 if n is not specified. If the file does not
exist, it is created.
Chapter 3: Basic Shell Features
42
3.7 Executing Commands
3.7.1 Simple Command Expansion
When a simple command is executed, the shell performs the following expansions, assign-
ments, and redirections, from left to right, in the following order.
1. The words that the parser has marked as variable assignments (those preceding the
command name) and redirections are saved for later processing.
2. The words that are not variable assignments or redirections are expanded (see
Section 3.5 [Shell Expansions], page 24).
If any words remain after expansion, the
first word is taken to be the name of the command and the remaining words are the
arguments.
3. Redirections are performed as described above (see Section 3.6 [Redirections], page 38).
4. The text after the in each variable assignment undergoes tilde expansion, parameter
expansion, command substitution, arithmetic expansion, and quote removal before
being assigned to the variable.
If no command name results, the variable assignments affect the current shell environ-
ment.
In the case of such a command (one that consists only of assignment statements
and redirections), assignment statements are performed before redirections. Otherwise, the
variables are added to the environment of the executed command and do not affect the cur-
rent shell environment. If any of the assignments attempts to assign a value to a readonly
variable, an error occurs, and the command exits with a non-zero status.
If no command name results, redirections are performed, but do not affect the current
shell environment. A redirection error causes the command to exit with a non-zero status.
If there is a command name left after expansion, execution proceeds as described below.
Otherwise, the command exits. If one of the expansions contained a command substitu-
tion, the exit status of the command is the exit status of the last command substitution
performed. If there were no command substitutions, the command exits with a status of
zero.
3.7.2 Command Search and Execution
After a command has been split into words, if it results in a simple command and an
optional list of arguments, the following actions are taken.
1. If the command name contains no slashes, the shell attempts to locate it. If there exists
a shell function by that name, that function is invoked as described in Section 3.3 [Shell
Functions], page 19.
2. If the name does not match a function, the shell searches for it in the list of shell
builtins. If a match is found, that builtin is invoked.
3. If the name is neither a shell function nor a builtin, and contains no slashes, Bash
searches each element of $PATH for a directory containing an executable file by that
name. Bash uses a hash table to remember the full pathnames of executable files to
avoid multiple PATH searches (see the description of hash in Section 4.1 [Bourne Shell
Builtins], page 48). A full search of the directories in $PATH is performed only if the
command is not found in the hash table. If the search is unsuccessful, the shell searches
for a defined shell function named command_not_found_handle. If that function exists,
Chapter 3: Basic Shell Features
43
it is invoked in a separate execution environment with the original command and the
original commands exit status becomes
the exit status of that subshell. If that function is not defined, the shell prints an error
message and returns an exit status of 127.
4. If the search is successful, or if the command name contains one or more slashes, the
shell executes the named program in a separate execution environment. Argument 0
is set to the name given, and the remaining arguments to the command are set to the
arguments supplied, if any.
5. If this execution fails because the file is not in executable format, and the file is not
a directory, it is assumed to be a shell script and the shell executes it as described in
Section 3.8 [Shell Scripts], page 46.
6. If the command was not begun asynchronously, the shell waits for the command to
complete and collects its exit status.
3.7.3 Command Execution Environment
The shell has an execution environment, which consists of the following:
the current working directory as set by cd, pushd, or popd, or inherited by the shell at
invocation
s parent
shell parameters that are set by variable assignment or with set or inherited from the
shell shell functions defined during execution or inherited from the shell options enabled at invocation (either by default or with command-line arguments) or
by set
shell aliases defined with alias (see Section 6.6 [Aliases], page 100)
the shell the current working directory
shell variables and functions marked for export, along with variables exported for the
command, passed in the environment (see Section 3.7.4 [Environment], page 44)
s parent, and
traps ignored by the shell are ignored
Chapter 3: Basic Shell Features
44
A command invoked in this separate environment cannot affect the shells execution environment.
Subshells spawned to execute command substitutions inherit the value of the -e option
from the parent shell. When not in posix mode, Bash clears the -e option in such subshells.
If a command is followed by a and job control is not active, the default standard input
for the command is the empty file /dev/null. Otherwise, the invoked command inherits
the file descriptors of the calling shell as modified by redirections.
3.7.4 Environment
When a program is invoked it is given an array of strings called the environment. This is a
list of name-value pairs, of the form name=value.
Bash provides several ways to manipulate the environment. On invocation, the shell
scans its own environment and creates a parameter for each name found, automatically
marking it for export to child processes. Executed commands inherit the environment. The
export and commands allow parameters and functions to be added to and
deleted from the environment. If the value of a parameter in the environment is modified, the
new value becomes part of the environment, replacing the old. The environment inherited
by any executed command consists of the shellexport -ndeclare -x$_s purposes, a command which exits with a zero exit status has succeeded.
A non-zero exit status indicates failure. This seemingly counter-intuitive scheme is used so
there is one well-defined way to indicate success and a variety of ways to indicate various
failure modes. When a command terminates on a fatal signal whose number is N, Bash
uses the value 128+N as the exit status.
If a command is not found, the child process created to execute it returns a status of
127. If a command is found but is not executable, the return status is 126.
If a command fails because of an error during expansion or redirection, the exit status
is greater than zero.
The exit status is used by the Bash conditional commands (see Section 3.2.5.2 [Con-
ditional Constructs], page 12) and some of the list constructs (see Section 3.2.4 [Lists],
page 10).
All of the Bash builtins return an exit status of zero if they succeed and a non-zero
status on failure, so they may be used by the conditional and list constructs. All builtins
return an exit status of 2 to indicate incorrect usage, generally invalid options or missing
arguments.
The exit status of the last command is available in the special parameter $?
(see
Section 3.4.2 [Special Parameters], page 23).
3.7.6 Signals
When Bash is interactive, in the absence of any traps, it ignores SIGTERM (so that does not kill an interactive shell), and SIGINT is caught and handled (so that the wait
builtin is interruptible). When Bash receives a SIGINT, it breaks out of any executing loops.
In all cases, Bash ignores SIGQUIT. If job control is in effect (see Chapter 7 [Job Control],
page 113), Bash ignores SIGTTIN, SIGTTOU, and SIGTSTP.
Non-builtin commands started by Bash have signal handlers set to the values inherited
by the shell from its parent. When job control is not in effect, asynchronous commands
ignore SIGINT and SIGQUIT in addition to these inherited handlers. Commands run as a
result of command substitution ignore the keyboard-generated job control signals SIGTTIN,
SIGTTOU, and SIGTSTP.
The shell exits by default upon receipt of a SIGHUP. Before exiting, an interactive shell
resends the SIGHUP to all jobs, running or stopped. Stopped jobs are sent SIGCONT to
ensure that they receive the SIGHUP. To prevent the shell from sending the SIGHUP signal
to a particular job, it should be removed from the jobs table with the disown builtin (see
Section 7.2 [Job Control Builtins], page 114) or marked to not receive SIGHUP using disown
-h.
If the huponexit shell option has been set with shopt (see Section 4.3.2 [The Shopt
Builtin], page 71), Bash sends a SIGHUP to all jobs when an interactive login shell exits.
If Bash is waiting for a command to complete and receives a signal for which a trap
has been set, the trap will not be executed until the command completes. When Bash is
waiting for an asynchronous command via the wait builtin, the reception of a signal for
which a trap has been set will cause the wait builtin to return immediately with an exit
status greater than 128, immediately after which the trap is executed.
When job control is not enabled, and Bash is waiting for a foreground command to
complete, the shell receives keyboard-generated signals such as SIGINT (usually generated
by ) that users commonly intend to send to that command. This happens because the
shell and the command are in the same process group as the terminal, and sends SIGINT
to all processes in that process group. See Chapter 7 [Job Control], page 113, for a more
in-depth discussion of process groups.
When Bash is running without job control enabled and receives SIGINT while waiting
for a foreground command, it waits until that foreground command terminates and then
decides what to do about the SIGINT:
1. If the command terminates due to the SIGINT, Bash concludes that the user meant to
end the entire script, and acts on the SIGINT (e.g., by running a SIGINT trap or exiting
itself);
2. If the pipeline does not terminate due to SIGINT, the program handled the SIGINT
itself and did not treat it as a fatal signal. In that case, Bash does not treat SIGINT
as a fatal signal, either, instead assuming that the SIGINT was used as part of the
programs command execution
mechanism. If the first line of a script begins with the two characters , the remainder
of the line specifies an interpreter for the program and, depending on the operating system,
one or more optional arguments for that interpreter. Thus, you can specify Bash, awk, Perl,
or some other interpreter and write the rest of the script file in that language.
The arguments to the interpreter consist of one or more optional arguments following
the interpreter name on the first line of the script file, followed by the name of the script
file, followed by the rest of the arguments supplied to the script. The details of how the
interpreter line is split into an interpreter name and a set of arguments vary across systems.
Bash will perform this action on operating systems that do not handle it themselves. Note
that some older versions of Unix limit the interpreter name and a single argument to a
maximum of 32 characters, so its a common idiom to use env to find bash even if it-----------:......--s parent. If n is omitted, the
exit status is that of the last command executed. Any trap on EXIT is executed
before the shell terminates.
export [-fn] [-p] [name[=value]]
Mark each name to be passed to child processes in the environment.
If the
-f option is supplied, the names refer to shell functions; otherwise the names
refer to shell variables. The -n option means to no longer mark each name for
export. If no names are supplied, or if the -p option is given, a list of names
of all exported variables is displayed. The -p option displays output in a form
that may be reused as input. If a variable name is followed by =value, the value
of the variable is set to value.
The return status is zero unless an invalid option is supplied, one of the names
is not a valid shell variable name, or -f is supplied with a name that is not a
shell function.
getopts optstring name [arg ...]
getopts is used by shell scripts to parse positional parameters. optstring con-
tains the option characters to be recognized; if a character is followed by a
colon, the option is expected to have an argument, which should be separated
from it by whitespace. The colon () and question mark () may not be
used as option characters. Each time it is invoked, getopts places the next
option in the shell variable name, initializing name if it does not exist, and the
index of the next argument to be processed into the variable OPTIND. OPTIND
is initialized to 1 each time the shell or a shell script is invoked. When an
Chapter 4: Shell Builtin Commands
51
option requires an argument, getopts places that argument into the variable
OPTARG. The shell does not reset OPTIND automatically; it must be manually
reset between multiple calls to getopts within the same shell invocation if a
new set of parameters is to be used.
When the end of options is encountered, getopts exits with a return value
greater than zero. OPTIND is set to the index of the first non-option argument,
and name is set to .
getopts normally parses the positional parameters, but if more arguments are
supplied as arg values, getopts parses those instead.
getopts can report errors in two ways. If the first character of optstring is a
colon, silent error reporting is used. In normal operation, diagnostic messages
are printed when invalid options or missing option arguments are encountered.
If the variable OPTERR is set to 0, no error messages will be displayed, even if
the first character of optstring is not a colon.
If an invalid option is seen, getopts places into name and, if not silent,
prints an error message and unsets OPTARG.
If getopts is silent, the option
character found is placed in OPTARG and no diagnostic message is printed.
If a required argument is not found, and getopts is not silent, a question mark
() is placed in name, OPTARG is unset, and a diagnostic message is printed. If
getopts is silent, then a colon () is placed in name and OPTARG is set to the
option character found.
hash [-r] [-p filename] [-dt] [name]
Each time hash is invoked, it remembers the full pathnames of the commands
specified as name arguments, so they need not be searched for on subsequent
invocations. The commands are found by searching through the directories
listed in $PATH. Any previously-remembered pathname is discarded. The -p
option inhibits the path search, and filename is used as the location of name.
The -r option causes the shell to forget all remembered locations. The -d
option causes the shell to forget the remembered location of each name. If the
-t option is supplied, the full pathname to which each name corresponds is
printed. If multiple name arguments are supplied with -t, the name is printed
before the hashed full pathname. The -l option causes output to be displayed
in a format that may be reused as input. If no arguments are given, or if only -l
is supplied, information about remembered commands is printed. The return
status is zero unless a name is not found or an invalid option is supplied.
hash
pwd
pwd [-LP]
Print the absolute pathname of the current working directory. If the -P option
is supplied, the pathname printed will not contain symbolic links.
If the -L
option is supplied, the pathname printed may contain symbolic links. The
return status is zero unless an error is encountered while determining the name
of the current directory or an invalid option is supplied.
readonly [-aAf] [-p] [name[=value]] ...
Mark each name as readonly. The values of these names may not be changed
by subsequent assignment. If the -f option is supplied, each name refers to
a shell function. The -a option means each name refers to an indexed array
variable; the -A option means each name refers to an associative array variable.
If both options are supplied, -A takes precedence. If no name arguments are
given, or if the -p option is supplied, a list of all readonly names is printed.
The other options may be used to restrict the output to a subset of the set of
readonly names. The -p option causes output to be displayed in a format that
may be reused as input. If a variable name is followed by =value, the value of
the variable is set to value. The return status is zero unless an invalid option
is supplied, one of the name arguments is not a valid shell variable or function
name, or the -f option is supplied with a name that is not a shell function.
return
return [n]
Cause a shell function to stop executing and return the value n to its caller.
If n is not supplied, the return value is the exit status of the last command
executed in the function.
If return is executed by a trap handler, the last
command used to determine the status is the last command executed before
the trap handler. If return is executed during a DEBUG trap, the last command
used to determine the status is the last command executed by the trap handler
before return was invoked. return may also be used to terminate execution of
a script being executed with the . (source) builtin, returning either n or the
exit status of the last command executed within the script as the exit status
of the script. If n is supplied, the return value is its least significant 8 bits.
Any command associated with the RETURN trap is executed before execution
resumes after the function or script. The return status is non-zero if return is
supplied a non-numeric argument or is used outside a function and not during
the execution of a script by . or source.
shift
shift [n]
Shift the positional parameters to the left by n. The positional parameters
from n+1 . . . $# are renamed to $1 . . . $#-n. Parameters represented by the
numbers $# down to $#-n+1 are unset. n must be a non-negative number less
than or equal to $#. If n is zero or greater than $#, the positional parameters
are not changed. If n is not supplied, it is assumed to be 1. The return status
is zero unless n is greater than $# or less than zero, non-zero otherwise.
test
[
test expr
Evaluate a conditional expression expr and return a status of 0 (true) or 1
(false). Each operator and operand must be a separate argument. Expressions
are composed of the primaries described below in Section 6.4 [Bash Conditional
Chapter 4: Shell Builtin Commands
53
Expressions], page 96. test does not accept any options, nor does it accept
and ignore an argument of -- as signifying the end of options.
When the [ form is used, the last argument to the command must be a ].
Expressions may be combined using the following operators, listed in decreasing
order of precedence. The evaluation depends on the number of arguments; see
below. Operator precedence is used when there are five or more arguments.
! expr
( expr )
expr1 -a expr2
expr1 -o expr2
The test and [ builtins evaluate conditional expressions using a set of rules
based on the number of arguments.
0 arguments
The expression is false.
1 argument
The expression is true if, and only if, the argument is not null.
2 arguments
If the first argument is , the expression is true if and only if the
second argument is null. If the first argument is one of the unary
conditional operators (see Section 6.4 [Bash Conditional Expres-
sions], page 96), the expression is true if the unary test is true. If
the first argument is not a valid unary operator, the expression is
false.
3 arguments
The following conditions are applied in the order listed.
1. If the second argument is one of the binary conditional opera-
tors (see Section 6.4 [Bash Conditional Expressions], page 96),
the result of the expression is the result of the binary test using
the first and third arguments as operands. The and
operators are considered binary operators when there are three
arguments.
2. If the first argument is , the value is the negation of the
two-argument test using the second and third arguments.
3. If the first argument is exactly and the third argument is
exactly , the result is the one-argument test of the second
argument.
4. Otherwise, the expression is false.
Chapter 4: Shell Builtin Commands
times
trap
4 arguments
The following conditions are applied in the order listed.
1. If the first argument is , the result is the negation of the
three-argument expression composed of the remaining argu-
ments.
2. If the first argument is exactly and the fourth argument is
exactly , the result is the two-argument test of the second
and third arguments.
3. Otherwise, the expression is parsed and evaluated according to
precedence using the rules listed above.
5 or more arguments
The expression is parsed and evaluated according to precedence
using the rules listed above.
When used with test or , the and operators sort lexicographically
using ASCII ordering.
times
Print out the user and system times used by the shell and its children. The
return status is zero.
trap [-lp] [arg] [sigspec ...]
The commands in arg are to be read and executed when the shell receives
signal sigspec. If arg is absent (and there is a single sigspec) or equal to ,
each specified signals return status is being inverted using !. These are the same
conditions obeyed by the errexit (-e) option.
Signals ignored upon entry to the shell cannot be trapped or reset. Trapped
signals that are not being ignored are reset to their original values in a subshell
or subshell environment when one is created.
The return status is zero unless a sigspec does not specify a valid signal.
umask
umask [-p] [-S] [mode]
Set the shell process"\C-x\C-r":re-read-init-filecommand lss value. The nameref
attribute cannot be applied to array variables.
Make names readonly. These names cannot then be assigned values
by subsequent assignment statements or unset.
Give each name the trace attribute. Traced functions inherit the
DEBUG and RETURN traps from the calling shell. The trace attribute
has no special meaning for variables.
When the variable is assigned a value, all lower-case characters are
converted to upper-case. The lower-case attribute is disabled.
Mark each name for export to subsequent commands via the envi-
ronment.