Skip to content

Commit 5076cac

Browse files
committed
Arrays concept part 2
1 parent f941181 commit 5076cac

File tree

5 files changed

+258
-0
lines changed

5 files changed

+258
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"authors": [
3+
"glennj"
4+
],
5+
"contributors": [
6+
"kotp",
7+
"IsaacG"
8+
],
9+
"blurb": "More about Arrays in Bash programs."
10+
}

concepts/more-arrays/about.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# About
2+
3+
TODO
Lines changed: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
1+
# More about Arrays
2+
3+
We were introduced to arrays in the [Arrays][arrays] chapter.
4+
This document will show more ways to use arrays.
5+
6+
## Concatenating the Elements of an Array into a Single String
7+
8+
In the previous Arrays chapter, you saw `"${myarray[@]}"`, with the `@` index, to expand the array into the individual elements.
9+
But sometimes you want to join all the elements into a single string.
10+
For this, use the `*` index:
11+
12+
```bash
13+
echo "${myarray[*]}"
14+
```
15+
16+
You are required to enclose the expansion in double quotes.
17+
18+
Bash uses the _first character_ of the `IFS` builtin variable as the separator character.
19+
By default, `$IFS` consists of space, tab and newline.
20+
21+
```bash
22+
myarray=(one two three four)
23+
mystring="${myarray[*]}"
24+
declare -p mystring
25+
# => declare -- mystring="one two three four"
26+
```
27+
28+
We can manipulate the `IFS` variable to use a different separator character:
29+
30+
```bash
31+
myarray=(one two three four)
32+
IFS=","
33+
mystring="${myarray[*]}"
34+
declare -p mystring
35+
# => declare -- mystring="one,two,three,four"
36+
```
37+
38+
~~~~exercism/advanced
39+
We can encapsulate this into a function.
40+
41+
```bash
42+
join() {
43+
local IFS=$1
44+
shift
45+
local elements=("$@")
46+
echo "${elements[*]}"
47+
}
48+
49+
join ":" "${myarray[@]}" # note, the "@" index
50+
# => "one:two:three:four"
51+
```
52+
53+
Localizing `IFS` in the function means we don't have to save the old value and restore it back to it's previous value in the global scope.
54+
55+
As a refinement, the special parameter `"$*"`, when quoted, has the same functionality so we don't need to save a copy of the function's arguments:
56+
57+
```bash
58+
join() {
59+
local IFS=$1
60+
shift
61+
echo "$*"
62+
}
63+
```
64+
~~~~
65+
66+
## Array Slices
67+
68+
You may have seen the `"${variable:offset:length}"` [parameter expansion][parameter-expansion] that expands into a _substring_ of the variable's value.
69+
We can do the same thing with arrays to expand a slice of the array.
70+
71+
```bash
72+
myarray=(one two three four)
73+
74+
subarray=("${myarray[@]:0:2}")
75+
declare -p subarray # => subarray=([0]="one" [1]="two")
76+
77+
subarray=("${myarray[@]:1:3}")
78+
declare -p subarray # => subarray=([0]="two" [1]="three" [2]="four")
79+
```
80+
81+
Omitting the length part means "from the offset to the end of the array":
82+
83+
```bash
84+
subarray=("${myarray[@]:2}")
85+
declare -p subarray # => subarray=([0]="three" [1]="four")
86+
```
87+
88+
## Passing an Array to a Function
89+
90+
This is not as straightforward as other languages you might be know.
91+
There are 3 techniques to pass an array to a function, and only one of them allows you to "mutate" the array that was passed.
92+
93+
### Pass the Elements
94+
95+
In the first technique, you just pass the array's values and collect them into a local array in the function.
96+
97+
```bash
98+
myfunc() {
99+
local array_copy=("$@")
100+
# do stuff with array_copy
101+
declare -p array_copy
102+
}
103+
104+
array_original=(11 22 33 44)
105+
myfunc "${array_original[@]}"
106+
```
107+
108+
The function's array holds a copy of the values.
109+
Any changes made to the array in the function are not reflected in the outer scope.
110+
111+
### Pass the Array Name
112+
113+
For these two techniques, you pass the array _name_ as a string.
114+
115+
#### 1. Using Indirect Expansion
116+
117+
Suppose you have variable `x=5` and variable `y=x`, and you want to use the `y` variable to get the value `5`.
118+
Some other languages let you do `$$y` but not Bash.
119+
Bash has a technique called **indirect expansion** (described in the manual in [Shell Parameter Expansion][parameter-expansion]).
120+
In bash, this uses the `!` character in a different way than we have seen before:
121+
122+
```bash
123+
x=5
124+
y=x
125+
echo "the value is ${!y}"
126+
```
127+
128+
We will use this technique to pass the array _name_ to the function, and indirectly access the values to make a copy them
129+
130+
```bash
131+
myfunc() {
132+
local array_name=$1
133+
local temp="${array_name}[@]"
134+
local array_copy=("${!temp}")
135+
# do stuff with array_copy
136+
declare -p array_copy
137+
}
138+
139+
array_original=(11 22 33 44)
140+
myfunc "array_original"
141+
```
142+
143+
This technique is quite messy.
144+
The `temp` variable will contain the _string_ `"array_original[@]"`.
145+
Then the indirect expansion expands to the global array's values.
146+
147+
The function's array holds a copy of the values.
148+
Any changes made to the array in the function are not reflected in the outer scope.
149+
150+
#### 2. Using a "nameref" Variable
151+
152+
This technique is more like the "pass by reference" capability you might be used to.
153+
We will pass the array name to the function.
154+
The function will create a local variable with the "nameref" attribute.
155+
This local array and the global array (whose name we passed in) are _the same array_.
156+
157+
```bash
158+
myfunc() {
159+
local -n local_array=$1
160+
# do stuff with local_array
161+
# we can mutate it
162+
local_array+=(55 66 77)
163+
}
164+
165+
array_original=(11 22 33 44)
166+
myfunc "array_original"
167+
168+
# show the mutated array
169+
declare -p array_original
170+
# => declare -a array_original=([0]="11" [1]="22" [2]="33" [3]="44" [4]="55" [5]="66" [6]="77")
171+
```
172+
173+
Namerefs also work with associative arrays, and "scalar" variables (that contain a string value).
174+
175+
~~~~exercism/note
176+
Inside the function, `declare -p local_array` is not extremely helpful.
177+
It will just emit `declare -n local_array="array_original"`.
178+
You can get the detailed information about the array by inspecting the passed-in array name: `declare -p "$1"`
179+
~~~~
180+
181+
~~~~exercism/caution
182+
Take care that the local array has a different name than the passed-in array.
183+
The code will still work, but it will emit "circular name reference" warnings like this:
184+
185+
```bash
186+
myfunc() {
187+
local -n a=$1
188+
local IFS=,
189+
echo "${a[*]}"
190+
}
191+
192+
# same name as the function's local variable
193+
a=(one two three)
194+
myfunc a
195+
```
196+
197+
```none
198+
bash: local: warning: a: circular name reference
199+
bash: warning: a: circular name reference
200+
bash: warning: a: circular name reference
201+
bash: warning: a: circular name reference
202+
one,two,three
203+
```
204+
~~~~
205+
206+
## The Positional Parameters are "Array-like"
207+
208+
In shells that aim to conform to the POSIX standard only (such as `ash` and `dash`), there are no arrays.
209+
The closest you can get is to use the positional parameters.
210+
211+
* The positional parameters are accessed by index: `$1`, `$2`, etc.
212+
* They are expanded into individual elements with `"$@"`
213+
* They are concatenated into a single string with `"$*"`
214+
* The number of parameters is `$#`
215+
216+
Use the `set` command to assign values to them:
217+
218+
```sh
219+
set -- one two three
220+
set -- "$@" four
221+
222+
for item in "$@"; do
223+
echo "do something with $item"
224+
done
225+
```
226+
227+
If your goal is to write "portable" shell scripts, you'll use the positional parameters to store a "list" of values.
228+
229+
[arrays]: https://exercism.org/tracks/bash/concepts/arrays
230+
[parameter-expansion]: https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion

concepts/more-arrays/links.json

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
[
2+
{
3+
"url": "https://www.gnu.org/software/bash/manual/bash.html#Arrays",
4+
"description": "\"Arrays\" in the bash manual"
5+
},
6+
{
7+
"url": "https://mywiki.wooledge.org/BashGuide/Arrays",
8+
"description": "\"Arrays\" in the Bash Guide"
9+
}
10+
]

config.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1284,6 +1284,11 @@
12841284
"uuid": "386b48d3-da82-448f-8607-8251367eb695",
12851285
"slug": "arithmetic",
12861286
"name": "Arithmetic"
1287+
},
1288+
{
1289+
"uuid": "6bfdc749-a40e-44a8-b26b-a402ba53624b",
1290+
"slug": "more-arrays",
1291+
"name": "More about Arrays"
12871292
}
12881293
],
12891294
"key_features": [

0 commit comments

Comments
 (0)