-
Notifications
You must be signed in to change notification settings - Fork 1
/
bash.info
9652 lines (7662 loc) · 399 KB
/
bash.info
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
This is bash.info, produced by makeinfo version 4.7 from
/Users/chet/src/bash/src/doc/bashref.texi.
This text is a brief description of the features that are present in
the Bash shell (version 3.2, 28 September 2006).
This is Edition 3.2, last updated 28 September 2006, of `The GNU
Bash Reference Manual', for `Bash', Version 3.2.
Copyright (C) 1988-2005 Free Software Foundation, Inc.
Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.
Permission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License,
Version 1.2 or any later version published by the Free Software
Foundation; with no Invariant Sections, with the Front-Cover texts
being "A GNU Manual," and with the Back-Cover Texts as in (a)
below. A copy of the license is included in the section entitled
"GNU Free Documentation License."
(a) The FSF's Back-Cover Text is: "You have freedom to copy and
modify this GNU Manual, like GNU software. Copies published by
the Free Software Foundation raise funds for GNU development."
INFO-DIR-SECTION Basics
START-INFO-DIR-ENTRY
* Bash: (bash). The GNU Bourne-Again SHell.
END-INFO-DIR-ENTRY
File: bash.info, Node: Top, Next: Introduction, Prev: (dir), Up: (dir)
Bash Features
*************
This text is a brief description of the features that are present in
the Bash shell (version 3.2, 28 September 2006).
This is Edition 3.2, last updated 28 September 2006, of `The GNU
Bash Reference Manual', for `Bash', Version 3.2.
Bash contains features that appear in other popular shells, and some
features that only appear in Bash. Some of the shells that Bash has
borrowed concepts from are the Bourne Shell (`sh'), the Korn Shell
(`ksh'), and the C-shell (`csh' and its successor, `tcsh'). The
following menu breaks the features up into categories based upon which
one of these other shells inspired the feature.
This manual is meant as a brief introduction to features found in
Bash. The Bash manual page should be used as the definitive reference
on shell behavior.
* Menu:
* Introduction:: An introduction to the shell.
* Definitions:: Some definitions used in the rest of this
manual.
* Basic Shell Features:: The shell "building blocks".
* Shell Builtin Commands:: Commands that are a part of the shell.
* Shell Variables:: Variables used or set by Bash.
* Bash Features:: Features found only in Bash.
* Job Control:: What job control is and how Bash allows you
to use it.
* Using History Interactively:: Command History Expansion
* Command Line Editing:: Chapter describing the command line
editing features.
* Installing Bash:: How to build and install Bash on your system.
* Reporting Bugs:: How to report bugs in Bash.
* Major Differences From The Bourne Shell:: A terse list of the differences
between Bash and historical
versions of /bin/sh.
* Copying This Manual:: Copying this manual.
* Builtin Index:: Index of Bash builtin commands.
* Reserved Word Index:: Index of Bash reserved words.
* Variable Index:: Quick reference helps you find the
variable you want.
* Function Index:: Index of bindable Readline functions.
* Concept Index:: General index for concepts described in
this manual.
File: bash.info, Node: Introduction, Next: Definitions, Prev: Top, Up: Top
1 Introduction
**************
* Menu:
* What is Bash?:: A short description of Bash.
* What is a shell?:: A brief introduction to shells.
File: bash.info, Node: What is Bash?, Next: What is a shell?, Up: Introduction
1.1 What is Bash?
=================
Bash is the shell, or command language interpreter, for the GNU
operating system. The name is an acronym for the `Bourne-Again SHell',
a pun on Stephen Bourne, the author of the direct ancestor of the
current Unix shell `sh', which appeared in the Seventh Edition Bell
Labs Research version of Unix.
Bash is largely compatible with `sh' and incorporates useful
features from the Korn shell `ksh' and the C shell `csh'. It is
intended to be a conformant implementation of the IEEE POSIX Shell and
Tools portion of the IEEE POSIX specification (IEEE Standard 1003.1).
It offers functional improvements over `sh' for both interactive and
programming use.
While the GNU operating system provides other shells, including a
version of `csh', Bash is the default shell. Like other GNU software,
Bash is quite portable. It currently runs on nearly every version of
Unix and a few other operating systems - independently-supported ports
exist for MS-DOS, OS/2, and Windows platforms.
File: bash.info, Node: What is a shell?, Prev: What is Bash?, Up: Introduction
1.2 What is a shell?
====================
At its base, a shell is simply a macro processor that executes
commands. The term macro processor means functionality where text and
symbols are expanded to create larger expressions.
A Unix shell is both a command interpreter and a programming
language. As a command interpreter, the shell provides the user
interface to the rich set of GNU utilities. The programming language
features allow these utilitites to be combined. Files containing
commands can be created, and become commands themselves. These new
commands have the same status as system commands in directories such as
`/bin', allowing users or groups to establish custom environments to
automate their common tasks.
Shells may be used interactively or non-interactively. In
interactive mode, they accept input typed from the keyboard. When
executing non-interactively, shells execute commands read from a file.
A shell allows execution of GNU commands, both synchronously and
asynchronously. The shell waits for synchronous commands to complete
before accepting more input; asynchronous commands continue to execute
in parallel with the shell while it reads and executes additional
commands. The "redirection" constructs permit fine-grained control of
the input and output of those commands. Moreover, the shell allows
control over the contents of commands' environments.
Shells also provide a small set of built-in commands ("builtins")
implementing functionality impossible or inconvenient to obtain via
separate utilities. For example, `cd', `break', `continue', and
`exec') cannot be implemented outside of the shell because they
directly manipulate the shell itself. The `history', `getopts',
`kill', or `pwd' builtins, among others, could be implemented in
separate utilities, but they are more convenient to use as builtin
commands. All of the shell builtins are described in subsequent
sections.
While executing commands is essential, most of the power (and
complexity) of shells is due to their embedded programming languages.
Like any high-level language, the shell provides variables, flow
control constructs, quoting, and functions.
Shells offer features geared specifically for interactive use rather
than to augment the programming language. These interactive features
include job control, command line editing, command history and aliases.
Each of these features is described in this manual.
File: bash.info, Node: Definitions, Next: Basic Shell Features, Prev: Introduction, Up: Top
2 Definitions
*************
These definitions are used throughout the remainder of this manual.
`POSIX'
A family of open system standards based on Unix. Bash is
primarily concerned with the Shell and Utilities portion of the
POSIX 1003.1 standard.
`blank'
A space or tab character.
`builtin'
A command that is implemented internally by the shell itself,
rather than by an executable program somewhere in the file system.
`control operator'
A `word' that performs a control function. It is a `newline' or
one of the following: `||', `&&', `&', `;', `;;', `|', `(', or `)'.
`exit status'
The value returned by a command to its caller. The value is
restricted to eight bits, so the maximum value is 255.
`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 `blank' or one of the following characters: `|', `&', `;',
`(', `)', `<', or `>'.
`name'
A `word' consisting solely of letters, numbers, and underscores,
and beginning with a letter or underscore. `Name's are used as
shell variable and function names. Also referred to as an
`identifier'.
`operator'
A `control operator' or a `redirection operator'. *Note
Redirections::, for a list of redirection operators.
`process group'
A collection of related processes each having the same process
group ID.
`process group ID'
A unique identifer that represents a `process group' during its
lifetime.
`reserved word'
A `word' that has a special meaning to the shell. Most reserved
words introduce shell flow control constructs, such as `for' and
`while'.
`return status'
A synonym for `exit status'.
`signal'
A mechanism by which a process may be notified by the kernel of an
event occurring in the system.
`special builtin'
A shell builtin command that has been classified as special by the
POSIX standard.
`token'
A sequence of characters considered a single unit by the shell.
It is either a `word' or an `operator'.
`word'
A `token' that is not an `operator'.
File: bash.info, Node: Basic Shell Features, Next: Shell Builtin Commands, Prev: Definitions, Up: Top
3 Basic Shell Features
**********************
Bash is an acronym for `Bourne-Again SHell'. The Bourne shell is the
traditional Unix shell originally written by Stephen Bourne. All of
the Bourne shell builtin commands are available in Bash, The rules for
evaluation and quoting are taken from the POSIX specification for the
`standard' Unix shell.
This chapter briefly summarizes the shell's `building blocks':
commands, control structures, shell functions, shell parameters, shell
expansions, redirections, which are a way to direct input and output
from and to named files, and how the shell executes commands.
* Menu:
* Shell Syntax:: What your input means to the shell.
* Shell Commands:: The types of commands you can use.
* Shell Functions:: Grouping commands by name.
* Shell Parameters:: How the shell stores values.
* Shell Expansions:: How Bash expands parameters and the various
expansions available.
* Redirections:: A way to control where input and output go.
* Executing Commands:: What happens when you run a command.
* Shell Scripts:: Executing files of shell commands.
File: bash.info, Node: Shell Syntax, Next: Shell Commands, Up: Basic Shell Features
3.1 Shell Syntax
================
* Menu:
* Shell Operation:: The basic operation of the shell.
* Quoting:: How to remove the special meaning from characters.
* Comments:: How to specify comments.
When the shell reads input, it proceeds through a sequence of
operations. If the input indicates the beginning of a comment, the
shell ignores the comment symbol (`#'), and the rest of that line.
Otherwise, roughly speaking, the shell reads its input and divides
the input into words and operators, employing the quoting rules to
select which meanings to assign various words and characters.
The shell then parses these tokens into commands and other
constructs, removes the special meaning of certain words or characters,
expands others, redirects input and output as needed, executes the
specified command, waits for the command's exit status, and makes that
exit status available for further inspection or processing.
File: bash.info, Node: Shell Operation, Next: Quoting, Up: Shell Syntax
3.1.1 Shell Operation
---------------------
The following is a brief description of the shell's operation when it
reads and executes a command. Basically, the shell does the following:
1. Reads its input from a file (*note Shell Scripts::), from a string
supplied as an argument to the `-c' invocation option (*note
Invoking Bash::), or from the user's terminal.
2. Breaks the input into words and operators, obeying the quoting
rules described in *Note Quoting::. These tokens are separated by
`metacharacters'. Alias expansion is performed by this step
(*note Aliases::).
3. Parses the tokens into simple and compound commands (*note Shell
Commands::).
4. Performs the various shell expansions (*note Shell Expansions::),
breaking the expanded tokens into lists of filenames (*note
Filename Expansion::) and commands and arguments.
5. Performs any necessary redirections (*note Redirections::) and
removes the redirection operators and their operands from the
argument list.
6. Executes the command (*note Executing Commands::).
7. Optionally waits for the command to complete and collects its exit
status (*note Exit Status::).
File: bash.info, Node: Quoting, Next: Comments, Prev: Shell Operation, Up: Shell Syntax
3.1.2 Quoting
-------------
* Menu:
* Escape Character:: How to remove the special meaning from a single
character.
* Single Quotes:: How to inhibit all interpretation of a sequence
of characters.
* Double Quotes:: How to suppress most of the interpretation of a
sequence of characters.
* ANSI-C Quoting:: How to expand ANSI-C sequences in quoted strings.
* Locale Translation:: How to translate strings into different languages.
Quoting is used to remove the special meaning of certain characters
or words to the shell. Quoting can be used to disable special
treatment for special characters, to prevent reserved words from being
recognized as such, and to prevent parameter expansion.
Each of the shell metacharacters (*note Definitions::) has special
meaning to the shell and must be quoted if it is to represent itself.
When the command history expansion facilities are being used (*note
History Interaction::), the HISTORY EXPANSION character, usually `!',
must be quoted to prevent history expansion. *Note Bash History
Facilities::, for more details concerning history expansion.
There are three quoting mechanisms: the ESCAPE CHARACTER, single
quotes, and double quotes.
File: bash.info, Node: Escape Character, Next: Single Quotes, Up: Quoting
3.1.2.1 Escape Character
........................
A non-quoted backslash `\' is the Bash escape character. It preserves
the literal value of the next character that follows, with the
exception of `newline'. If a `\newline' pair appears, and the
backslash itself is not quoted, the `\newline' is treated as a line
continuation (that is, it is removed from the input stream and
effectively ignored).
File: bash.info, Node: Single Quotes, Next: Double Quotes, Prev: Escape Character, Up: Quoting
3.1.2.2 Single Quotes
.....................
Enclosing characters in single quotes (`'') preserves the literal value
of each character within the quotes. A single quote may not occur
between single quotes, even when preceded by a backslash.
File: bash.info, Node: Double Quotes, Next: ANSI-C Quoting, Prev: Single Quotes, Up: Quoting
3.1.2.3 Double Quotes
.....................
Enclosing characters in double quotes (`"') preserves the literal value
of all characters within the quotes, with the exception of `$', ``',
`\', and, when history expansion is enabled, `!'. The characters `$'
and ``' retain their special meaning within double quotes (*note Shell
Expansions::). The backslash retains its special meaning only when
followed by one of the following characters: `$', ``', `"', `\', or
`newline'. Within double quotes, backslashes that are followed by one
of these characters are removed. Backslashes preceding characters
without a special meaning are left unmodified. A double quote may be
quoted within double quotes by preceding it with a backslash. If
enabled, history expansion will be performed unless an `!' appearing in
double quotes is escaped using a backslash. The backslash preceding
the `!' is not removed.
The special parameters `*' and `@' have special meaning when in
double quotes (*note Shell Parameter Expansion::).
File: bash.info, Node: ANSI-C Quoting, Next: Locale Translation, Prev: Double Quotes, Up: Quoting
3.1.2.4 ANSI-C Quoting
......................
Words of the form `$'STRING'' are treated specially. The word expands
to STRING, with backslash-escaped characters replaced as specified by
the ANSI C standard. Backslash escape sequences, if present, are
decoded as follows:
`\a'
alert (bell)
`\b'
backspace
`\e'
an escape character (not ANSI C)
`\f'
form feed
`\n'
newline
`\r'
carriage return
`\t'
horizontal tab
`\v'
vertical tab
`\\'
backslash
`\''
single quote
`\NNN'
the eight-bit character whose value is the octal value NNN (one to
three digits)
`\xHH'
the eight-bit character whose value is the hexadecimal value HH
(one or two hex digits)
`\cX'
a control-X character
The expanded result is single-quoted, as if the dollar sign had not
been present.
File: bash.info, Node: Locale Translation, Prev: ANSI-C Quoting, Up: Quoting
3.1.2.5 Locale-Specific Translation
...................................
A double-quoted string preceded by a dollar sign (`$') will cause the
string to be translated according to the current locale. If the
current locale is `C' or `POSIX', the dollar sign is ignored. If the
string is translated and replaced, the replacement is double-quoted.
Some systems use the message catalog selected by the `LC_MESSAGES'
shell variable. Others create the name of the message catalog from the
value of the `TEXTDOMAIN' shell variable, possibly adding a suffix of
`.mo'. If you use the `TEXTDOMAIN' variable, you may need to set the
`TEXTDOMAINDIR' variable to the location of the message catalog files.
Still others use both variables in this fashion:
`TEXTDOMAINDIR'/`LC_MESSAGES'/LC_MESSAGES/`TEXTDOMAIN'.mo.
File: bash.info, Node: Comments, Prev: Quoting, Up: Shell Syntax
3.1.3 Comments
--------------
In a non-interactive shell, or an interactive shell in which the
`interactive_comments' option to the `shopt' builtin is enabled (*note
Bash Builtins::), a word beginning with `#' causes that word and all
remaining characters on that line to be ignored. An interactive shell
without the `interactive_comments' option enabled does not allow
comments. The `interactive_comments' option is on by default in
interactive shells. *Note Interactive Shells::, for a description of
what makes a shell interactive.
File: bash.info, Node: Shell Commands, Next: Shell Functions, Prev: Shell Syntax, Up: Basic Shell Features
3.2 Shell Commands
==================
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.
* Menu:
* Simple Commands:: The most common type of command.
* Pipelines:: Connecting the input and output of several
commands.
* Lists:: How to execute commands sequentially.
* Compound Commands:: Shell commands for control flow.
File: bash.info, Node: Simple Commands, Next: Pipelines, Up: Shell Commands
3.2.1 Simple Commands
---------------------
A simple command is the kind of command encountered most often. It's
just a sequence of words separated by `blank's, terminated by one of
the shell's control operators (*note Definitions::). The first word
generally specifies a command to be executed, with the rest of the
words being that command's arguments.
The return status (*note Exit Status::) 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.
File: bash.info, Node: Pipelines, Next: Lists, Prev: Simple Commands, Up: Shell Commands
3.2.2 Pipelines
---------------
A `pipeline' is a sequence of simple commands separated by `|'.
The format for a pipeline is
[`time' [`-p']] [`!'] COMMAND1 [`|' 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 output.
The reserved word `time' causes timing statistics to be printed for
the pipeline once it finishes. The statistics currently consist of
elapsed (wall-clock) time and user and system time consumed by the
command's execution. The `-p' option changes the output format to that
specified by POSIX. The `TIMEFORMAT' variable may be set to a format
string that specifies how the timing information should be displayed.
*Note Bash Variables::, 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.
If the pipeline is not executed asynchronously (*note Lists::), the
shell waits for all commands in the pipeline to complete.
Each command in a pipeline is executed in its own subshell (*note
Command Execution Environment::). The exit status of a pipeline is the
exit status of the last command in the pipeline, unless the `pipefail'
option is enabled (*note The Set Builtin::). If `pipefail' is enabled,
the pipeline's return status is the value of the last (rightmost)
command to exit with a non-zero status, or zero if all commands exit
successfully. If the reserved word `!' precedes the pipeline, the exit
status is the logical negation of the exit status as described above.
The shell waits for all commands in the pipeline to terminate before
returning a value.
File: bash.info, Node: Lists, Next: Compound Commands, Prev: Pipelines, Up: Shell Commands
3.2.3 Lists of Commands
-----------------------
A `list' is a sequence of one or more pipelines separated by one of the
operators `;', `&', `&&', or `||', and optionally terminated by one of
`;', `&', or a `newline'.
Of these list operators, `&&' and `||' have equal precedence,
followed by `;' and `&', which have equal precedence.
A sequence of one or more newlines may appear in a `list' to delimit
commands, equivalent to a semicolon.
If a command is terminated by the control operator `&', the shell
executes the command asynchronously in a subshell. This is known as
executing the command in the BACKGROUND. The shell does not wait for
the command to finish, and the return status is 0 (true). When job
control is not active (*note Job Control::), the standard input for
asynchronous commands, in the absence of any explicit redirections, is
redirected from `/dev/null'.
Commands separated by a `;' are executed sequentially; the shell
waits for each command to terminate in turn. The return status is the
exit status of the last command executed.
The control operators `&&' and `||' denote AND lists and OR lists,
respectively. An AND list has the form
COMMAND1 && COMMAND2
COMMAND2 is executed if, and only if, COMMAND1 returns an exit status
of zero.
An OR list has the form
COMMAND1 || COMMAND2
COMMAND2 is executed if, and only if, COMMAND1 returns a non-zero exit
status.
The return status of AND and OR lists is the exit status of the last
command executed in the list.
File: bash.info, Node: Compound Commands, Prev: Lists, Up: Shell Commands
3.2.4 Compound Commands
-----------------------
* Menu:
* Looping Constructs:: Shell commands for iterative action.
* Conditional Constructs:: Shell commands for conditional execution.
* Command Grouping:: Ways to group commands.
Compound commands are the shell programming constructs. Each
construct begins with a reserved word or control operator and is
terminated by a corresponding reserved word or operator. Any
redirections (*note Redirections::) associated with a compound command
apply to all commands within that compound command unless explicitly
overridden.
Bash provides looping constructs, conditional commands, and
mechanisms to group commands and execute them as a unit.
File: bash.info, Node: Looping Constructs, Next: Conditional Constructs, Up: Compound Commands
3.2.4.1 Looping Constructs
..........................
Bash supports the following looping constructs.
Note that wherever a `;' appears in the description of a command's
syntax, it may be replaced with one or more newlines.
`until'
The syntax of the `until' command is:
until TEST-COMMANDS; do CONSEQUENT-COMMANDS; done
Execute CONSEQUENT-COMMANDS as long as TEST-COMMANDS has an exit
status which is not zero. The return status is the exit status of
the last command executed in CONSEQUENT-COMMANDS, or zero if none
was executed.
`while'
The syntax of the `while' command is:
while TEST-COMMANDS; do CONSEQUENT-COMMANDS; done
Execute CONSEQUENT-COMMANDS as long as TEST-COMMANDS has an exit
status of zero. The return status is the exit status of the last
command executed in CONSEQUENT-COMMANDS, or zero if none was
executed.
`for'
The syntax of the `for' command is:
for NAME [in WORDS ...]; do COMMANDS; done
Expand WORDS, and execute COMMANDS once for each member in the
resultant list, with NAME bound to the current member. If `in
WORDS' is not present, the `for' command executes the COMMANDS
once for each positional parameter that is set, as if `in "$@"'
had been specified (*note Special Parameters::). The return
status is the exit status of the last command that executes. If
there are no items in the expansion of WORDS, no commands are
executed, and the return status is zero.
An alternate form of the `for' command is also supported:
for (( EXPR1 ; EXPR2 ; EXPR3 )) ; do COMMANDS ; done
First, the arithmetic expression EXPR1 is evaluated according to
the rules described below (*note Shell Arithmetic::). The
arithmetic expression EXPR2 is then evaluated repeatedly until it
evaluates to zero. Each time EXPR2 evaluates to a non-zero value,
COMMANDS are executed and the arithmetic expression EXPR3 is
evaluated. If any expression is omitted, it behaves as if it
evaluates to 1. The return value is the exit status of the last
command in LIST that is executed, or false if any of the
expressions is invalid.
The `break' and `continue' builtins (*note Bourne Shell Builtins::)
may be used to control loop execution.
File: bash.info, Node: Conditional Constructs, Next: Command Grouping, Prev: Looping Constructs, Up: Compound Commands
3.2.4.2 Conditional Constructs
..............................
`if'
The syntax of the `if' command is:
if TEST-COMMANDS; then
CONSEQUENT-COMMANDS;
[elif MORE-TEST-COMMANDS; then
MORE-CONSEQUENTS;]
[else ALTERNATE-CONSEQUENTS;]
fi
The TEST-COMMANDS list is executed, and if its return status is
zero, the CONSEQUENT-COMMANDS list is executed. If TEST-COMMANDS
returns a non-zero status, each `elif' list is executed in turn,
and if its exit status is zero, the corresponding MORE-CONSEQUENTS
is executed and the command completes. If `else
ALTERNATE-CONSEQUENTS' is present, and the final command in the
final `if' or `elif' clause has a non-zero exit status, then
ALTERNATE-CONSEQUENTS is executed. The return status is the exit
status of the last command executed, or zero if no condition
tested true.
`case'
The syntax of the `case' command is:
`case WORD in [ [(] PATTERN [| PATTERN]...) COMMAND-LIST ;;]... esac'
`case' will selectively execute the COMMAND-LIST corresponding to
the first PATTERN that matches WORD. If the shell option
`nocasematch' (see the description of `shopt' in *Note Bash
Builtins::) is enabled, the match is performed without regard to
the case of alphabetic characters. The `|' is used to separate
multiple patterns, and the `)' operator terminates a pattern list.
A list of patterns and an associated command-list is known as a
CLAUSE. Each clause must be terminated with `;;'. The WORD
undergoes tilde expansion, parameter expansion, command
substitution, arithmetic expansion, and quote removal before
matching is attempted. Each PATTERN undergoes tilde expansion,
parameter expansion, command substitution, and arithmetic
expansion.
There may be an arbitrary number of `case' clauses, each terminated
by a `;;'. The first pattern that matches determines the
command-list that is executed.
Here is an example using `case' in a script that could be used to
describe one interesting feature of an animal:
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."
The return status is zero if no PATTERN is matched. Otherwise, the
return status is the exit status of the COMMAND-LIST executed.
`select'
The `select' construct allows the easy generation of menus. It
has almost the same syntax as the `for' command:
select NAME [in WORDS ...]; do COMMANDS; done
The list of words following `in' is expanded, generating a list of
items. The set of expanded words is printed on the standard error
output stream, each preceded by a number. If the `in WORDS' is
omitted, the positional parameters are printed, as if `in "$@"'
had been specifed. The `PS3' prompt is then displayed and a line
is read from the standard input. If the line consists of a number
corresponding to one of the displayed words, then the value of
NAME is set to that word. If the line is empty, the words and
prompt are displayed again. If `EOF' is read, the `select'
command completes. Any other value read causes NAME to be set to
null. The line read is saved in the variable `REPLY'.
The COMMANDS are executed after each selection until a `break'
command is executed, at which point the `select' command completes.
Here is an example that allows the user to pick a filename from the
current directory, and displays the name and index of the file
selected.
select fname in *;
do
echo you picked $fname \($REPLY\)
break;
done
`((...))'
(( EXPRESSION ))
The arithmetic EXPRESSION is evaluated according to the rules
described below (*note Shell Arithmetic::). If the value of the
expression is non-zero, the return status is 0; otherwise the
return status is 1. This is exactly equivalent to
let "EXPRESSION"
*Note Bash Builtins::, for a full description of the `let' builtin.
`[[...]]'
[[ EXPRESSION ]]
Return a status of 0 or 1 depending on the evaluation of the
conditional expression EXPRESSION. Expressions are composed of
the primaries described below in *Note Bash Conditional
Expressions::. Word splitting and filename expansion are not
performed on the words between the `[[' and `]]'; tilde expansion,
parameter and variable expansion, arithmetic expansion, command
substitution, process substitution, and quote removal are
performed. Conditional operators such as `-f' must be unquoted to
be recognized as primaries.
When the `==' and `!=' operators are used, the string to the right
of the operator is considered a pattern and matched according to
the rules described below in *Note Pattern Matching::. If the
shell option `nocasematch' (see the description of `shopt' in
*Note Bash Builtins::) is enabled, the match is performed without
regard to the case of alphabetic characters. The return value is
0 if the string matches (`==') or does not match (`!=')the
pattern, and 1 otherwise. Any part of the pattern may be quoted
to force it to be matched as a string.
An additional binary operator, `=~', is available, with the same
precedence as `==' and `!='. When it is used, the string to the
right of the operator is considered an extended regular expression
and matched accordingly (as in regex3)). The return value is 0 if
the string matches the pattern, and 1 otherwise. If the regular
expression is syntactically incorrect, the conditional
expression's return value is 2. If the shell option `nocasematch'
(see the description of `shopt' in *Note Bash Builtins::) is
enabled, the match is performed without regard to the case of
alphabetic characters. Substrings matched by parenthesized
subexpressions within the regular expression are saved in the
array variable `BASH_REMATCH'. The element of `BASH_REMATCH' with
index 0 is the portion of the string matching the entire regular
expression. The element of `BASH_REMATCH' with index N is the
portion of the string matching the Nth parenthesized subexpression.
Expressions may be combined using the following operators, listed
in decreasing order of precedence:
`( EXPRESSION )'
Returns the value of EXPRESSION. This may be used to
override the normal precedence of operators.
`! EXPRESSION'
True if EXPRESSION is false.
`EXPRESSION1 && EXPRESSION2'
True if both EXPRESSION1 and EXPRESSION2 are true.
`EXPRESSION1 || EXPRESSION2'
True if either EXPRESSION1 or EXPRESSION2 is true.
The `&&' and `||' operators do not evaluate EXPRESSION2 if the
value of EXPRESSION1 is sufficient to determine the return value
of the entire conditional expression.
File: bash.info, Node: Command Grouping, Prev: Conditional Constructs, Up: Compound Commands
3.2.4.3 Grouping Commands
.........................
Bash provides two ways to group a list of commands to be executed as a
unit. When commands are grouped, redirections may be applied to the
entire command list. For example, the output of all the commands in
the list may be redirected to a single stream.
`()'
( LIST )
Placing a list of commands between parentheses causes a subshell
environment to be created (*note Command Execution Environment::),
and each of the commands in LIST to be executed in that subshell.
Since the LIST is executed in a subshell, variable assignments do
not remain in effect after the subshell completes.
`{}'
{ LIST; }
Placing a list of commands between curly braces causes the list to
be executed in the current shell context. No subshell is created.
The semicolon (or newline) following LIST is required.
In addition to the creation of a subshell, there is a subtle
difference between these two constructs due to historical reasons. The
braces are `reserved words', so they must be separated from the LIST by
`blank's. The parentheses are `operators', and are recognized as
separate tokens by the shell even if they are not separated from the
LIST by whitespace.
The exit status of both of these constructs is the exit status of
LIST.
File: bash.info, Node: Shell Functions, Next: Shell Parameters, Prev: Shell Commands, Up: Basic Shell Features
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:
[ `function' ] NAME () COMPOUND-COMMAND [ REDIRECTIONS ]
This defines a shell function named NAME. 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 (*note Compound Commands::). That command is
usually a LIST enclosed between { and }, but may be any compound
command listed above. COMPOUND-COMMAND is executed whenever NAME is
specified as the name of a command. Any redirections (*note
Redirections::) 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 (*note Bourne Shell Builtins::).
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 `blank's or newlines. This is because the braces are
reserved words and are only recognized as such when they are separated
by whitespace. 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 parameters during its execution (*note Positional
Parameters::). 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 the exception that 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). *Note
Bourne Shell Builtins::, for the description of the `trap' builtin.
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 function's execution. If
a numeric argument is given to `return', that is the function's return
status; otherwise the function's return status is the exit status of
the last command executed before the `return'.
Variables local to the function may be declared with the `local'
builtin. These variables are visible only to the function and the
commands it invokes.
Function names and definitions may be listed with the `-f' option to
the `declare' or `typeset' builtin commands (*note Bash Builtins::).
The `-F' option to `declare' or `typeset' will list the function names
only (and optionally the source file and line number, if the `extdebug'
shell option is enabled). Functions may be exported so that subshells
automatically have them defined with the `-f' option to the `export'
builtin (*note Bourne Shell Builtins::). Note that shell functions and
variables with the same name may result in multiple identically-named
entries in the environment passed to the shell's children. Care should