Debian Codegraph @

basics-reviewed.bash

raw symbols SCIP
1 #!/bin/bash
2 # basics-reviewed.bash
3
4 # File extension == *.bash == specific to Bash
5
6 # Copyright (c) Michael S. Zick, 2003; All rights reserved.
7 # License: Use in any form, for any purpose.
8 # Revision: $ID$
9 #
10 # Edited for layout by M.C.
11 # (author of the "Advanced Bash Scripting Guide")
12 # Fixes and updates (04/08) by Cliff Bamford.
13
14
15 # This script tested under Bash versions 2.04, 2.05a and 2.05b.
16 # It may not work with earlier versions.
17 # This demonstration script generates one --intentional--
18 #+ "command not found" error message. See line 436.
19
20 # The current Bash maintainer, Chet Ramey, has fixed the items noted
21 #+ for later versions of Bash.
22
23
24
25 ###-------------------------------------------###
26 ### Pipe the output of this script to 'more' ###
27 ###+ else it will scroll off the page. ###
28 ### ###
29 ### You may also redirect its output ###
30 ###+ to a file for examination. ###
31 ###-------------------------------------------###
32
33
34
35 # Most of the following points are described at length in
36 #+ the text of the foregoing "Advanced Bash Scripting Guide."
37 # This demonstration script is mostly just a reorganized presentation.
38 # -- msz
39
40 # Variables are not typed unless otherwise specified.
41
42 # Variables are named. Names must contain a non-digit.
43 # File descriptor names (as in, for example: 2>&1)
44 #+ contain ONLY digits.
45
46 # Parameters and Bash array elements are numbered.
47 # (Parameters are very similar to Bash arrays.)
48
49 # A variable name may be undefined (null reference).
50 unset VarNull
51
52 # A variable name may be defined but empty (null contents).
53 VarEmpty='' # Two, adjacent, single quotes.
54
55 # A variable name may be defined and non-empty.
56 VarSomething='Literal'
57
58 # A variable may contain:
59 # * A whole number as a signed 32-bit (or larger) integer
60 # * A string
61 # A variable may also be an array.
62
63 # A string may contain embedded blanks and may be treated
64 #+ as if it where a function name with optional arguments.
65
66 # The names of variables and the names of functions
67 #+ are in different namespaces.
68
69
70 # A variable may be defined as a Bash array either explicitly or
71 #+ implicitly by the syntax of the assignment statement.
72 # Explicit:
73 declare -a ArrayVar
74
75
76
77 # The echo command is a builtin.
78 echo $VarSomething
79
80 # The printf command is a builtin.
81 # Translate %s as: String-Format
82 printf %s $VarSomething # No linebreak specified, none output.
83 echo # Default, only linebreak output.
84
85
86
87
88 # The Bash parser word breaks on whitespace.
89 # Whitespace, or the lack of it is significant.
90 # (This holds true in general; there are, of course, exceptions.)
91
92
93
94
95 # Translate the DOLLAR_SIGN character as: Content-Of.
96
97 # Extended-Syntax way of writing Content-Of:
98 echo ${VarSomething}
99
100 # The ${ ... } Extended-Syntax allows more than just the variable
101 #+ name to be specified.
102 # In general, $VarSomething can always be written as: ${VarSomething}.
103
104 # Call this script with arguments to see the following in action.
105
106
107
108 # Outside of double-quotes, the special characters @ and *
109 #+ specify identical behavior.
110 # May be pronounced as: All-Elements-Of.
111
112 # Without specification of a name, they refer to the
113 #+ pre-defined parameter Bash-Array.
114
115
116
117 # Glob-Pattern references
118 echo $* # All parameters to script or function
119 echo ${*} # Same
120
121 # Bash disables filename expansion for Glob-Patterns.
122 # Only character matching is active.
123
124
125 # All-Elements-Of references
126 echo $@ # Same as above
127 echo ${@} # Same as above
128
129
130
131
132 # Within double-quotes, the behavior of Glob-Pattern references
133 #+ depends on the setting of IFS (Input Field Separator).
134 # Within double-quotes, All-Elements-Of references behave the same.
135
136
137 # Specifying only the name of a variable holding a string refers
138 #+ to all elements (characters) of a string.
139
140
141 # To specify an element (character) of a string,
142 #+ the Extended-Syntax reference notation (see below) MAY be used.
143
144
145
146
147 # Specifying only the name of a Bash array references
148 #+ the subscript zero element,
149 #+ NOT the FIRST DEFINED nor the FIRST WITH CONTENTS element.
150
151 # Additional qualification is needed to reference other elements,
152 #+ which means that the reference MUST be written in Extended-Syntax.
153 # The general form is: ${name[subscript]}.
154
155 # The string forms may also be used: ${name:subscript}
156 #+ for Bash-Arrays when referencing the subscript zero element.
157
158
159 # Bash-Arrays are implemented internally as linked lists,
160 #+ not as a fixed area of storage as in some programming languages.
161
162
163 # Characteristics of Bash arrays (Bash-Arrays):
164 # --------------------------------------------
165
166 # If not otherwise specified, Bash-Array subscripts begin with
167 #+ subscript number zero. Literally: [0]
168 # This is called zero-based indexing.
169 ###
170 # If not otherwise specified, Bash-Arrays are subscript packed
171 #+ (sequential subscripts without subscript gaps).
172 ###
173 # Negative subscripts are not allowed.
174 ###
175 # Elements of a Bash-Array need not all be of the same type.
176 ###
177 # Elements of a Bash-Array may be undefined (null reference).
178 # That is, a Bash-Array may be "subscript sparse."
179 ###
180 # Elements of a Bash-Array may be defined and empty (null contents).
181 ###
182 # Elements of a Bash-Array may contain:
183 # * A whole number as a signed 32-bit (or larger) integer
184 # * A string
185 # * A string formated so that it appears to be a function name
186 # + with optional arguments
187 ###
188 # Defined elements of a Bash-Array may be undefined (unset).
189 # That is, a subscript packed Bash-Array may be changed
190 # + into a subscript sparse Bash-Array.
191 ###
192 # Elements may be added to a Bash-Array by defining an element
193 #+ not previously defined.
194 ###
195 # For these reasons, I have been calling them "Bash-Arrays".
196 # I'll return to the generic term "array" from now on.
197 # -- msz
198
199
200 echo "========================================================="
201
202 # Lines 202 - 334 supplied by Cliff Bamford. (Thanks!)
203 # Demo --- Interaction with Arrays, quoting, IFS, echo, * and @ ---
204 #+ all affect how things work
205
206 ArrayVar[0]='zero' # 0 normal
207 ArrayVar[1]=one # 1 unquoted literal
208 ArrayVar[2]='two' # 2 normal
209 ArrayVar[3]='three' # 3 normal
210 ArrayVar[4]='I am four' # 4 normal with spaces
211 ArrayVar[5]='five' # 5 normal
212 unset ArrayVar[6] # 6 undefined
213 ArrayValue[7]='seven' # 7 normal
214 ArrayValue[8]='' # 8 defined but empty
215 ArrayValue[9]='nine' # 9 normal
216
217
218 echo '--- Here is the array we are using for this test'
219 echo
220 echo "ArrayVar[0]='zero' # 0 normal"
221 echo "ArrayVar[1]=one # 1 unquoted literal"
222 echo "ArrayVar[2]='two' # 2 normal"
223 echo "ArrayVar[3]='three' # 3 normal"
224 echo "ArrayVar[4]='I am four' # 4 normal with spaces"
225 echo "ArrayVar[5]='five' # 5 normal"
226 echo "unset ArrayVar[6] # 6 undefined"
227 echo "ArrayValue[7]='seven' # 7 normal"
228 echo "ArrayValue[8]='' # 8 defined but empty"
229 echo "ArrayValue[9]='nine' # 9 normal"
230 echo
231
232
233 echo
234 echo '---Case0: No double-quotes, Default IFS of space,tab,newline ---'
235 IFS=$'\x20'$'\x09'$'\x0A' # In exactly this order.
236 echo 'Here is: printf %q {${ArrayVar[*]}'
237 printf %q ${ArrayVar[*]}
238 echo
239 echo 'Here is: printf %q {${ArrayVar[@]}'
240 printf %q ${ArrayVar[@]}
241 echo
242 echo 'Here is: echo ${ArrayVar[*]}'
243 echo ${ArrayVar[@]}
244 echo 'Here is: echo {${ArrayVar[@]}'
245 echo ${ArrayVar[@]}
246
247 echo
248 echo '---Case1: Within double-quotes - Default IFS of space-tab-
249 newline ---'
250 IFS=$'\x20'$'\x09'$'\x0A' # These three bytes,
251 echo 'Here is: printf %q "{${ArrayVar[*]}"'
252 printf %q "${ArrayVar[*]}"
253 echo
254 echo 'Here is: printf %q "{${ArrayVar[@]}"'
255 printf %q "${ArrayVar[@]}"
256 echo
257 echo 'Here is: echo "${ArrayVar[*]}"'
258 echo "${ArrayVar[@]}"
259 echo 'Here is: echo "{${ArrayVar[@]}"'
260 echo "${ArrayVar[@]}"
261
262 echo
263 echo '---Case2: Within double-quotes - IFS is q'
264 IFS='q'
265 echo 'Here is: printf %q "{${ArrayVar[*]}"'
266 printf %q "${ArrayVar[*]}"
267 echo
268 echo 'Here is: printf %q "{${ArrayVar[@]}"'
269 printf %q "${ArrayVar[@]}"
270 echo
271 echo 'Here is: echo "${ArrayVar[*]}"'
272 echo "${ArrayVar[@]}"
273 echo 'Here is: echo "{${ArrayVar[@]}"'
274 echo "${ArrayVar[@]}"
275
276 echo
277 echo '---Case3: Within double-quotes - IFS is ^'
278 IFS='^'
279 echo 'Here is: printf %q "{${ArrayVar[*]}"'
280 printf %q "${ArrayVar[*]}"
281 echo
282 echo 'Here is: printf %q "{${ArrayVar[@]}"'
283 printf %q "${ArrayVar[@]}"
284 echo
285 echo 'Here is: echo "${ArrayVar[*]}"'
286 echo "${ArrayVar[@]}"
287 echo 'Here is: echo "{${ArrayVar[@]}"'
288 echo "${ArrayVar[@]}"
289
290 echo
291 echo '---Case4: Within double-quotes - IFS is ^ followed by
292 space,tab,newline'
293 IFS=$'^'$'\x20'$'\x09'$'\x0A' # ^ + space tab newline
294 echo 'Here is: printf %q "{${ArrayVar[*]}"'
295 printf %q "${ArrayVar[*]}"
296 echo
297 echo 'Here is: printf %q "{${ArrayVar[@]}"'
298 printf %q "${ArrayVar[@]}"
299 echo
300 echo 'Here is: echo "${ArrayVar[*]}"'
301 echo "${ArrayVar[@]}"
302 echo 'Here is: echo "{${ArrayVar[@]}"'
303 echo "${ArrayVar[@]}"
304
305 echo
306 echo '---Case6: Within double-quotes - IFS set and empty '
307 IFS=''
308 echo 'Here is: printf %q "{${ArrayVar[*]}"'
309 printf %q "${ArrayVar[*]}"
310 echo
311 echo 'Here is: printf %q "{${ArrayVar[@]}"'
312 printf %q "${ArrayVar[@]}"
313 echo
314 echo 'Here is: echo "${ArrayVar[*]}"'
315 echo "${ArrayVar[@]}"
316 echo 'Here is: echo "{${ArrayVar[@]}"'
317 echo "${ArrayVar[@]}"
318
319 echo
320 echo '---Case7: Within double-quotes - IFS is unset'
321 unset IFS
322 echo 'Here is: printf %q "{${ArrayVar[*]}"'
323 printf %q "${ArrayVar[*]}"
324 echo
325 echo 'Here is: printf %q "{${ArrayVar[@]}"'
326 printf %q "${ArrayVar[@]}"
327 echo
328 echo 'Here is: echo "${ArrayVar[*]}"'
329 echo "${ArrayVar[@]}"
330 echo 'Here is: echo "{${ArrayVar[@]}"'
331 echo "${ArrayVar[@]}"
332
333 echo
334 echo '---End of Cases---'
335 echo "========================================================="; echo
336
337
338
339 # Put IFS back to the default.
340 # Default is exactly these three bytes.
341 IFS=$'\x20'$'\x09'$'\x0A' # In exactly this order.
342
343 # Interpretation of the above outputs:
344 # A Glob-Pattern is I/O; the setting of IFS matters.
345 ###
346 # An All-Elements-Of does not consider IFS settings.
347 ###
348 # Note the different output using the echo command and the
349 #+ quoted format operator of the printf command.
350
351
352 # Recall:
353 # Parameters are similar to arrays and have the similar behaviors.
354 ###
355 # The above examples demonstrate the possible variations.
356 # To retain the shape of a sparse array, additional script
357 #+ programming is required.
358 ###
359 # The source code of Bash has a routine to output the
360 #+ [subscript]=value array assignment format.
361 # As of version 2.05b, that routine is not used,
362 #+ but that might change in future releases.
363
364
365
366 # The length of a string, measured in non-null elements (characters):
367 echo
368 echo '- - Non-quoted references - -'
369 echo 'Non-Null character count: '${#VarSomething}' characters.'
370
371 # test='Lit'$'\x00''eral' # $'\x00' is a null character.
372 # echo ${#test} # See that?
373
374
375
376 # The length of an array, measured in defined elements,
377 #+ including null content elements.
378 echo
379 echo 'Defined content count: '${#ArrayVar[@]}' elements.'
380 # That is NOT the maximum subscript (4).
381 # That is NOT the range of the subscripts (1 . . 4 inclusive).
382 # It IS the length of the linked list.
383 ###
384 # Both the maximum subscript and the range of the subscripts may
385 #+ be found with additional script programming.
386
387 # The length of a string, measured in non-null elements (characters):
388 echo
389 echo '- - Quoted, Glob-Pattern references - -'
390 echo 'Non-Null character count: '"${#VarSomething}"' characters.'
391
392 # The length of an array, measured in defined elements,
393 #+ including null-content elements.
394 echo
395 echo 'Defined element count: '"${#ArrayVar[*]}"' elements.'
396
397 # Interpretation: Substitution does not effect the ${# ... } operation.
398 # Suggestion:
399 # Always use the All-Elements-Of character
400 #+ if that is what is intended (independence from IFS).
401
402
403
404 # Define a simple function.
405 # I include an underscore in the name
406 #+ to make it distinctive in the examples below.
407 ###
408 # Bash separates variable names and function names
409 #+ in different namespaces.
410 # The Mark-One eyeball isn't that advanced.
411 ###
412 _simple() {
413 echo -n 'SimpleFunc'$@ # Newlines are swallowed in
414 } #+ result returned in any case.
415
416
417 # The ( ... ) notation invokes a command or function.
418 # The $( ... ) notation is pronounced: Result-Of.
419
420
421 # Invoke the function _simple
422 echo
423 echo '- - Output of function _simple - -'
424 _simple # Try passing arguments.
425 echo
426 # or
427 (_simple) # Try passing arguments.
428 echo
429
430 echo '- Is there a variable of that name? -'
431 echo $_simple not defined # No variable by that name.
432
433 # Invoke the result of function _simple (Error msg intended)
434
435 ###
436 $(_simple) # Gives an error message:
437 # line 436: SimpleFunc: command not found
438 # ---------------------------------------
439
440 echo
441 ###
442
443 # The first word of the result of function _simple
444 #+ is neither a valid Bash command nor the name of a defined function.
445 ###
446 # This demonstrates that the output of _simple is subject to evaluation.
447 ###
448 # Interpretation:
449 # A function can be used to generate in-line Bash commands.
450
451
452 # A simple function where the first word of result IS a bash command:
453 ###
454 _print() {
455 echo -n 'printf %q '$@
456 }
457
458 echo '- - Outputs of function _print - -'
459 _print parm1 parm2 # An Output NOT A Command.
460 echo
461
462 $(_print parm1 parm2) # Executes: printf %q parm1 parm2
463 # See above IFS examples for the
464 #+ various possibilities.
465 echo
466
467 $(_print $VarSomething) # The predictable result.
468 echo
469
470
471
472 # Function variables
473 # ------------------
474
475 echo
476 echo '- - Function variables - -'
477 # A variable may represent a signed integer, a string or an array.
478 # A string may be used like a function name with optional arguments.
479
480 # set -vx # Enable if desired
481 declare -f funcVar #+ in namespace of functions
482
483 funcVar=_print # Contains name of function.
484 $funcVar parm1 # Same as _print at this point.
485 echo
486
487 funcVar=$(_print ) # Contains result of function.
488 $funcVar # No input, No output.
489 $funcVar $VarSomething # The predictable result.
490 echo
491
492 funcVar=$(_print $VarSomething) # $VarSomething replaced HERE.
493 $funcVar # The expansion is part of the
494 echo #+ variable contents.
495
496 funcVar="$(_print $VarSomething)" # $VarSomething replaced HERE.
497 $funcVar # The expansion is part of the
498 echo #+ variable contents.
499
500 # The difference between the unquoted and the double-quoted versions
501 #+ above can be seen in the "protect_literal.sh" example.
502 # The first case above is processed as two, unquoted, Bash-Words.
503 # The second case above is processed as one, quoted, Bash-Word.
504
505
506
507
508 # Delayed replacement
509 # -------------------
510
511 echo
512 echo '- - Delayed replacement - -'
513 funcVar="$(_print '$VarSomething')" # No replacement, single Bash-Word.
514 eval $funcVar # $VarSomething replaced HERE.
515 echo
516
517 VarSomething='NewThing'
518 eval $funcVar # $VarSomething replaced HERE.
519 echo
520
521 # Restore the original setting trashed above.
522 VarSomething=Literal
523
524 # There are a pair of functions demonstrated in the
525 #+ "protect_literal.sh" and "unprotect_literal.sh" examples.
526 # These are general purpose functions for delayed replacement literals
527 #+ containing variables.
528
529
530
531
532
533 # REVIEW:
534 # ------
535
536 # A string can be considered a Classic-Array of elements (characters).
537 # A string operation applies to all elements (characters) of the string
538 #+ (in concept, anyway).
539 ###
540 # The notation: ${array_name[@]} represents all elements of the
541 #+ Bash-Array: array_name.
542 ###
543 # The Extended-Syntax string operations can be applied to all
544 #+ elements of an array.
545 ###
546 # This may be thought of as a For-Each operation on a vector of strings.
547 ###
548 # Parameters are similar to an array.
549 # The initialization of a parameter array for a script
550 #+ and a parameter array for a function only differ
551 #+ in the initialization of ${0}, which never changes its setting.
552 ###
553 # Subscript zero of the script's parameter array contains
554 #+ the name of the script.
555 ###
556 # Subscript zero of a function's parameter array DOES NOT contain
557 #+ the name of the function.
558 # The name of the current function is accessed by the $FUNCNAME variable.
559 ###
560 # A quick, review list follows (quick, not short).
561
562 echo
563 echo '- - Test (but not change) - -'
564 echo '- null reference -'
565 echo -n ${VarNull-'NotSet'}' ' # NotSet
566 echo ${VarNull} # NewLine only
567 echo -n ${VarNull:-'NotSet'}' ' # NotSet
568 echo ${VarNull} # Newline only
569
570 echo '- null contents -'
571 echo -n ${VarEmpty-'Empty'}' ' # Only the space
572 echo ${VarEmpty} # Newline only
573 echo -n ${VarEmpty:-'Empty'}' ' # Empty
574 echo ${VarEmpty} # Newline only
575
576 echo '- contents -'
577 echo ${VarSomething-'Content'} # Literal
578 echo ${VarSomething:-'Content'} # Literal
579
580 echo '- Sparse Array -'
581 echo ${ArrayVar[@]-'not set'}
582
583 # ASCII-Art time
584 # State Y==yes, N==no
585 # - :-
586 # Unset Y Y ${# ... } == 0
587 # Empty N Y ${# ... } == 0
588 # Contents N N ${# ... } > 0
589
590 # Either the first and/or the second part of the tests
591 #+ may be a command or a function invocation string.
592 echo
593 echo '- - Test 1 for undefined - -'
594 declare -i t
595 _decT() {
596 t=$t-1
597 }
598
599 # Null reference, set: t == -1
600 t=${#VarNull} # Results in zero.
601 ${VarNull- _decT } # Function executes, t now -1.
602 echo $t
603
604 # Null contents, set: t == 0
605 t=${#VarEmpty} # Results in zero.
606 ${VarEmpty- _decT } # _decT function NOT executed.
607 echo $t
608
609 # Contents, set: t == number of non-null characters
610 VarSomething='_simple' # Set to valid function name.
611 t=${#VarSomething} # non-zero length
612 ${VarSomething- _decT } # Function _simple executed.
613 echo $t # Note the Append-To action.
614
615 # Exercise: clean up that example.
616 unset t
617 unset _decT
618 VarSomething=Literal
619
620 echo
621 echo '- - Test and Change - -'
622 echo '- Assignment if null reference -'
623 echo -n ${VarNull='NotSet'}' ' # NotSet NotSet
624 echo ${VarNull}
625 unset VarNull
626
627 echo '- Assignment if null reference -'
628 echo -n ${VarNull:='NotSet'}' ' # NotSet NotSet
629 echo ${VarNull}
630 unset VarNull
631
632 echo '- No assignment if null contents -'
633 echo -n ${VarEmpty='Empty'}' ' # Space only
634 echo ${VarEmpty}
635 VarEmpty=''
636
637 echo '- Assignment if null contents -'
638 echo -n ${VarEmpty:='Empty'}' ' # Empty Empty
639 echo ${VarEmpty}
640 VarEmpty=''
641
642 echo '- No change if already has contents -'
643 echo ${VarSomething='Content'} # Literal
644 echo ${VarSomething:='Content'} # Literal
645
646
647 # "Subscript sparse" Bash-Arrays
648 ###
649 # Bash-Arrays are subscript packed, beginning with
650 #+ subscript zero unless otherwise specified.
651 ###
652 # The initialization of ArrayVar was one way
653 #+ to "otherwise specify". Here is the other way:
654 ###
655 echo
656 declare -a ArraySparse
657 ArraySparse=( [1]=one [2]='' [4]='four' )
658 # [0]=null reference, [2]=null content, [3]=null reference
659
660 echo '- - Array-Sparse List - -'
661 # Within double-quotes, default IFS, Glob-Pattern
662
663 IFS=$'\x20'$'\x09'$'\x0A'
664 printf %q "${ArraySparse[*]}"
665 echo
666
667 # Note that the output does not distinguish between "null content"
668 #+ and "null reference".
669 # Both print as escaped whitespace.
670 ###
671 # Note also that the output does NOT contain escaped whitespace
672 #+ for the "null reference(s)" prior to the first defined element.
673 ###
674 # This behavior of 2.04, 2.05a and 2.05b has been reported
675 #+ and may change in a future version of Bash.
676
677 # To output a sparse array and maintain the [subscript]=value
678 #+ relationship without change requires a bit of programming.
679 # One possible code fragment:
680 ###
681 # local l=${#ArraySparse[@]} # Count of defined elements
682 # local f=0 # Count of found subscripts
683 # local i=0 # Subscript to test
684 ( # Anonymous in-line function
685 for (( l=${#ArraySparse[@]}, f = 0, i = 0 ; f < l ; i++ ))
686 do
687 # 'if defined then...'
688 ${ArraySparse[$i]+ eval echo '\ ['$i']='${ArraySparse[$i]} ; (( f++ )) }
689 done
690 )
691
692 # The reader coming upon the above code fragment cold
693 #+ might want to review "command lists" and "multiple commands on a line"
694 #+ in the text of the foregoing "Advanced Bash Scripting Guide."
695 ###
696 # Note:
697 # The "read -a array_name" version of the "read" command
698 #+ begins filling array_name at subscript zero.
699 # ArraySparse does not define a value at subscript zero.
700 ###
701 # The user needing to read/write a sparse array to either
702 #+ external storage or a communications socket must invent
703 #+ a read/write code pair suitable for their purpose.
704 ###
705 # Exercise: clean it up.
706
707 unset ArraySparse
708
709 echo
710 echo '- - Conditional alternate (But not change)- -'
711 echo '- No alternate if null reference -'
712 echo -n ${VarNull+'NotSet'}' '
713 echo ${VarNull}
714 unset VarNull
715
716 echo '- No alternate if null reference -'
717 echo -n ${VarNull:+'NotSet'}' '
718 echo ${VarNull}
719 unset VarNull
720
721 echo '- Alternate if null contents -'
722 echo -n ${VarEmpty+'Empty'}' ' # Empty
723 echo ${VarEmpty}
724 VarEmpty=''
725
726 echo '- No alternate if null contents -'
727 echo -n ${VarEmpty:+'Empty'}' ' # Space only
728 echo ${VarEmpty}
729 VarEmpty=''
730
731 echo '- Alternate if already has contents -'
732
733 # Alternate literal
734 echo -n ${VarSomething+'Content'}' ' # Content Literal
735 echo ${VarSomething}
736
737 # Invoke function
738 echo -n ${VarSomething:+ $(_simple) }' ' # SimpleFunc Literal
739 echo ${VarSomething}
740 echo
741
742 echo '- - Sparse Array - -'
743 echo ${ArrayVar[@]+'Empty'} # An array of 'Empty'(ies)
744 echo
745
746 echo '- - Test 2 for undefined - -'
747
748 declare -i t
749 _incT() {
750 t=$t+1
751 }
752
753 # Note:
754 # This is the same test used in the sparse array
755 #+ listing code fragment.
756
757 # Null reference, set: t == -1
758 t=${#VarNull}-1 # Results in minus-one.
759 ${VarNull+ _incT } # Does not execute.
760 echo $t' Null reference'
761
762 # Null contents, set: t == 0
763 t=${#VarEmpty}-1 # Results in minus-one.
764 ${VarEmpty+ _incT } # Executes.
765 echo $t' Null content'
766
767 # Contents, set: t == (number of non-null characters)
768 t=${#VarSomething}-1 # non-null length minus-one
769 ${VarSomething+ _incT } # Executes.
770 echo $t' Contents'
771
772 # Exercise: clean up that example.
773 unset t
774 unset _incT
775
776 # ${name?err_msg} ${name:?err_msg}
777 # These follow the same rules but always exit afterwards
778 #+ if an action is specified following the question mark.
779 # The action following the question mark may be a literal
780 #+ or a function result.
781 ###
782 # ${name?} ${name:?} are test-only, the return can be tested.
783
784
785
786
787 # Element operations
788 # ------------------
789
790 echo
791 echo '- - Trailing sub-element selection - -'
792
793 # Strings, Arrays and Positional parameters
794
795 # Call this script with multiple arguments
796 #+ to see the parameter selections.
797
798 echo '- All -'
799 echo ${VarSomething:0} # all non-null characters
800 echo ${ArrayVar[@]:0} # all elements with content
801 echo ${@:0} # all parameters with content;
802 # ignoring parameter[0]
803
804 echo
805 echo '- All after -'
806 echo ${VarSomething:1} # all non-null after character[0]
807 echo ${ArrayVar[@]:1} # all after element[0] with content
808 echo ${@:2} # all after param[1] with content
809
810 echo
811 echo '- Range after -'
812 echo ${VarSomething:4:3} # ral
813 # Three characters after
814 # character[3]
815
816 echo '- Sparse array gotch -'
817 echo ${ArrayVar[@]:1:2} # four - The only element with content.
818 # Two elements after (if that many exist).
819 # the FIRST WITH CONTENTS
820 #+ (the FIRST WITH CONTENTS is being
821 #+ considered as if it
822 #+ were subscript zero).
823 # Executed as if Bash considers ONLY array elements with CONTENT
824 # printf %q "${ArrayVar[@]:0:3}" # Try this one
825
826 # In versions 2.04, 2.05a and 2.05b,
827 #+ Bash does not handle sparse arrays as expected using this notation.
828 #
829 # The current Bash maintainer, Chet Ramey, has corrected this.
830
831
832 echo '- Non-sparse array -'
833 echo ${@:2:2} # Two parameters following parameter[1]
834
835 # New victims for string vector examples:
836 stringZ=abcABC123ABCabc
837 arrayZ=( abcabc ABCABC 123123 ABCABC abcabc )
838 sparseZ=( [1]='abcabc' [3]='ABCABC' [4]='' [5]='123123' )
839
840 echo
841 echo ' - - Victim string - -'$stringZ'- - '
842 echo ' - - Victim array - -'${arrayZ[@]}'- - '
843 echo ' - - Sparse array - -'${sparseZ[@]}'- - '
844 echo ' - [0]==null ref, [2]==null ref, [4]==null content - '
845 echo ' - [1]=abcabc [3]=ABCABC [5]=123123 - '
846 echo ' - non-null-reference count: '${#sparseZ[@]}' elements'
847
848 echo
849 echo '- - Prefix sub-element removal - -'
850 echo '- - Glob-Pattern match must include the first character. - -'
851 echo '- - Glob-Pattern may be a literal or a function result. - -'
852 echo
853
854
855 # Function returning a simple, Literal, Glob-Pattern
856 _abc() {
857 echo -n 'abc'
858 }
859
860 echo '- Shortest prefix -'
861 echo ${stringZ#123} # Unchanged (not a prefix).
862 echo ${stringZ#$(_abc)} # ABC123ABCabc
863 echo ${arrayZ[@]#abc} # Applied to each element.
864
865 # echo ${sparseZ[@]#abc} # Version-2.05b core dumps.
866 # Has since been fixed by Chet Ramey.
867
868 # The -it would be nice- First-Subscript-Of
869 # echo ${#sparseZ[@]#*} # This is NOT valid Bash.
870
871 echo
872 echo '- Longest prefix -'
873 echo ${stringZ##1*3} # Unchanged (not a prefix)
874 echo ${stringZ##a*C} # abc
875 echo ${arrayZ[@]##a*c} # ABCABC 123123 ABCABC
876
877 # echo ${sparseZ[@]##a*c} # Version-2.05b core dumps.
878 # Has since been fixed by Chet Ramey.
879
880 echo
881 echo '- - Suffix sub-element removal - -'
882 echo '- - Glob-Pattern match must include the last character. - -'
883 echo '- - Glob-Pattern may be a literal or a function result. - -'
884 echo
885 echo '- Shortest suffix -'
886 echo ${stringZ%1*3} # Unchanged (not a suffix).
887 echo ${stringZ%$(_abc)} # abcABC123ABC
888 echo ${arrayZ[@]%abc} # Applied to each element.
889
890 # echo ${sparseZ[@]%abc} # Version-2.05b core dumps.
891 # Has since been fixed by Chet Ramey.
892
893 # The -it would be nice- Last-Subscript-Of
894 # echo ${#sparseZ[@]%*} # This is NOT valid Bash.
895
896 echo
897 echo '- Longest suffix -'
898 echo ${stringZ%%1*3} # Unchanged (not a suffix)
899 echo ${stringZ%%b*c} # a
900 echo ${arrayZ[@]%%b*c} # a ABCABC 123123 ABCABC a
901
902 # echo ${sparseZ[@]%%b*c} # Version-2.05b core dumps.
903 # Has since been fixed by Chet Ramey.
904
905 echo
906 echo '- - Sub-element replacement - -'
907 echo '- - Sub-element at any location in string. - -'
908 echo '- - First specification is a Glob-Pattern - -'
909 echo '- - Glob-Pattern may be a literal or Glob-Pattern function result. - -'
910 echo '- - Second specification may be a literal or function result. - -'
911 echo '- - Second specification may be unspecified. Pronounce that'
912 echo ' as: Replace-With-Nothing (Delete) - -'
913 echo
914
915
916
917 # Function returning a simple, Literal, Glob-Pattern
918 _123() {
919 echo -n '123'
920 }
921
922 echo '- Replace first occurrence -'
923 echo ${stringZ/$(_123)/999} # Changed (123 is a component).
924 echo ${stringZ/ABC/xyz} # xyzABC123ABCabc
925 echo ${arrayZ[@]/ABC/xyz} # Applied to each element.
926 echo ${sparseZ[@]/ABC/xyz} # Works as expected.
927
928 echo
929 echo '- Delete first occurrence -'
930 echo ${stringZ/$(_123)/}
931 echo ${stringZ/ABC/}
932 echo ${arrayZ[@]/ABC/}
933 echo ${sparseZ[@]/ABC/}
934
935 # The replacement need not be a literal,
936 #+ since the result of a function invocation is allowed.
937 # This is general to all forms of replacement.
938 echo
939 echo '- Replace first occurrence with Result-Of -'
940 echo ${stringZ/$(_123)/$(_simple)} # Works as expected.
941 echo ${arrayZ[@]/ca/$(_simple)} # Applied to each element.
942 echo ${sparseZ[@]/ca/$(_simple)} # Works as expected.
943
944 echo
945 echo '- Replace all occurrences -'
946 echo ${stringZ//[b2]/X} # X-out b's and 2's
947 echo ${stringZ//abc/xyz} # xyzABC123ABCxyz
948 echo ${arrayZ[@]//abc/xyz} # Applied to each element.
949 echo ${sparseZ[@]//abc/xyz} # Works as expected.
950
951 echo
952 echo '- Delete all occurrences -'
953 echo ${stringZ//[b2]/}
954 echo ${stringZ//abc/}
955 echo ${arrayZ[@]//abc/}
956 echo ${sparseZ[@]//abc/}
957
958 echo
959 echo '- - Prefix sub-element replacement - -'
960 echo '- - Match must include the first character. - -'
961 echo
962
963 echo '- Replace prefix occurrences -'
964 echo ${stringZ/#[b2]/X} # Unchanged (neither is a prefix).
965 echo ${stringZ/#$(_abc)/XYZ} # XYZABC123ABCabc
966 echo ${arrayZ[@]/#abc/XYZ} # Applied to each element.
967 echo ${sparseZ[@]/#abc/XYZ} # Works as expected.
968
969 echo
970 echo '- Delete prefix occurrences -'
971 echo ${stringZ/#[b2]/}
972 echo ${stringZ/#$(_abc)/}
973 echo ${arrayZ[@]/#abc/}
974 echo ${sparseZ[@]/#abc/}
975
976 echo
977 echo '- - Suffix sub-element replacement - -'
978 echo '- - Match must include the last character. - -'
979 echo
980
981 echo '- Replace suffix occurrences -'
982 echo ${stringZ/%[b2]/X} # Unchanged (neither is a suffix).
983 echo ${stringZ/%$(_abc)/XYZ} # abcABC123ABCXYZ
984 echo ${arrayZ[@]/%abc/XYZ} # Applied to each element.
985 echo ${sparseZ[@]/%abc/XYZ} # Works as expected.
986
987 echo
988 echo '- Delete suffix occurrences -'
989 echo ${stringZ/%[b2]/}
990 echo ${stringZ/%$(_abc)/}
991 echo ${arrayZ[@]/%abc/}
992 echo ${sparseZ[@]/%abc/}
993
994 echo
995 echo '- - Special cases of null Glob-Pattern - -'
996 echo
997
998 echo '- Prefix all -'
999 # null substring pattern means 'prefix'
1000 echo ${stringZ/#/NEW} # NEWabcABC123ABCabc
1001 echo ${arrayZ[@]/#/NEW} # Applied to each element.
1002 echo ${sparseZ[@]/#/NEW} # Applied to null-content also.
1003 # That seems reasonable.
1004
1005 echo
1006 echo '- Suffix all -'
1007 # null substring pattern means 'suffix'
1008 echo ${stringZ/%/NEW} # abcABC123ABCabcNEW
1009 echo ${arrayZ[@]/%/NEW} # Applied to each element.
1010 echo ${sparseZ[@]/%/NEW} # Applied to null-content also.
1011 # That seems reasonable.
1012
1013 echo
1014 echo '- - Special case For-Each Glob-Pattern - -'
1015 echo '- - - - This is a nice-to-have dream - - - -'
1016 echo
1017
1018 _GenFunc() {
1019 echo -n ${0} # Illustration only.
1020 # Actually, that would be an arbitrary computation.
1021 }
1022
1023 # All occurrences, matching the AnyThing pattern.
1024 # Currently //*/ does not match null-content nor null-reference.
1025 # /#/ and /%/ does match null-content but not null-reference.
1026 echo ${sparseZ[@]//*/$(_GenFunc)}
1027
1028
1029 # A possible syntax would be to make
1030 #+ the parameter notation used within this construct mean:
1031 # ${1} - The full element
1032 # ${2} - The prefix, if any, to the matched sub-element
1033 # ${3} - The matched sub-element
1034 # ${4} - The suffix, if any, to the matched sub-element
1035 #
1036 # echo ${sparseZ[@]//*/$(_GenFunc ${3})} # Same as ${1} here.
1037 # Perhaps it will be implemented in a future version of Bash.
1038
1039
1040 exit 0