Debian Codegraph @

array-assign.bash

raw symbols SCIP
1 #! /bin/bashscip-shell filesystem . . `/bin/bash`.
2 # array-assign.bash
3
4 # Array operations are Bash-specific,
5 #+ hence the ".bash" in the script name.
6
7 # Copyright (c) Michael S. Zick, 2003, All rights reserved.
8 # License: Unrestricted reuse in any form, for any purpose.
9 # Version: $ID$
10 #
11 # Clarification and additional comments by William Park.
12
13 # Based on an example provided by Stephane Chazelas
14 #+ which appeared in an earlier version of the
15 #+ Advanced Bash Scripting Guide.
16
17 # Output format of the 'times' command:
18 # User CPU <space> System CPU
19 # User CPU of dead children <space> System CPU of dead children
20
21 # Bash has two versions of assigning all elements of an array
22 #+ to a new array variable.
23 # Both drop 'null reference' elements
24 #+ in Bash versions 2.04 and later.
25 # An additional array assignment that maintains the relationship of
26 #+ [subscript]=value for arrays may be added to newer versions.
27
28 # Constructs a large array using an internal command,
29 #+ but anything creating an array of several thousand elements
30 #+ will do just fine.
31
32 declare -a bigOne=( /dev/* ) # All the files in /dev . . .
33 echoscip-shell system . . echo.
34 echoscip-shell system . . echo. 'Conditions: Unquoted, default IFS, All-Elements-Of'
35 echoscip-shell system . . echo. "Number of elements in array is ${#bigOne[@]}"
36
37 # set -vx
38
39
40
41 echoscip-shell system . . echo.
42 echoscip-shell system . . echo. '- - testing: =( ${array[@]} ) - -'
43 times
44 declare -a bigTwo=( ${bigOne[@]} )
45 # Note parens: ^ ^
46 times
47
48
49 echoscip-shell system . . echo.
50 echoscip-shell system . . echo. '- - testing: =${array[@]} - -'
51 times
52 declare -a bigThree=${bigOne[@]}
53 # No parentheses this time.
54 times
55
56 # Comparing the numbers shows that the second form, pointed out
57 #+ by Stephane Chazelas, is faster.
58 #
59 # As William Park explains:
60 #+ The bigTwo array assigned element by element (because of parentheses),
61 #+ whereas bigThree assigned as a single string.
62 # So, in essence, you have:
63 # bigTwo=( [0]="..." [1]="..." [2]="..." ... )
64 # bigThree=( [0]="... ... ..." )
65 #
66 # Verify this by: echo ${bigTwo[0]}
67 # echo ${bigThree[0]}
68
69
70 # I will continue to use the first form in my example descriptions
71 #+ because I think it is a better illustration of what is happening.
72
73 # The reusable portions of my examples will actual contain
74 #+ the second form where appropriate because of the speedup.
75
76 # MSZ: Sorry about that earlier oversight folks.
77
78
79 # Note:
80 # ----
81 # The "declare -a" statements in lines 32 and 44
82 #+ are not strictly necessary, since it is implicit
83 #+ in the Array=( ... ) assignment form.
84 # However, eliminating these declarations slows down
85 #+ the execution of the following sections of the script.
86 # Try it, and see.
87
88 exit 0