Skip to content

Commit 35859d6

Browse files
committed
doc(styleguide,etc): describe empty-array nounset in Bash <= 4.3
1 parent 9fbe788 commit 35859d6

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

doc/api-and-naming.md

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,8 @@ The exit status is implementation-defined.
172172

173173
- The `_comp_compgen -- COMPGEN_ARGS` returns whether there is at least one
174174
completion. This is useful when one wants to reuse the array content with
175-
`"${tmp[@]}"` avoiding `nounset` error.
175+
`"${tmp[@]}"` avoiding `nounset` error in Bash 4.2 and 4.3 for an empty array
176+
`tmp`.
176177
- Some use other rules for the exit status. E.g., `help` and `usage` return
177178
whether there were options *before* filtering by cur. This is used for
178179
`_comp_compgen_help || _comp_compgen_usage`.
@@ -206,8 +207,8 @@ in `_comp_compgen_mygen1`.
206207
_comp_compgen_mygen1()
207208
{
208209
local -a arr=(1 2 3)
209-
_comp_compgen -av arr -- -W '4 5 6'
210-
_comp_compgen_set "${arr[@]/#p}"
210+
_comp_compgen -av arr -- -W '4 5 6' &&
211+
_comp_compgen_set "${arr[@]/#p}"
211212
}
212213

213214
_comp_compgen -v arr mygen1 # fails to get the result in array `arr`
@@ -222,8 +223,8 @@ assigning the final result.
222223
_comp_compgen_mygen1()
223224
{
224225
local -a arr=(1 2 3)
225-
_comp_compgen -av arr -- -W '4 5 6'
226-
_comp_compgen -U arr set "${arr[@]/#p}"
226+
_comp_compgen -av arr -- -W '4 5 6' &&
227+
_comp_compgen -U arr set "${arr[@]/#p}"
227228
}
228229
```
229230

doc/styleguide.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,16 @@ E.g. write `${foo[bar]}`, not `${foo[$bar]}`, and similarly `${foo[bar+1]}`
111111
vs `${foo[((bar+1))]}` or `${foo[$((bar+1))]}`, `${foo[--i]}` vs
112112
`${foo[((--i))]}`.
113113

114+
## `((${#array[@]})) && cmd "${array[@]}"`
115+
116+
When one uses the array expansion of the form `"${array[@]}"` or `${array[*]}`,
117+
please make sure that the `array` is not empty. This is because of a strange
118+
behavior of Bash <= 4.3, where `${array[@]}` and `${array[*]}` fail for the
119+
`nounset` error when `array` is an empty array. It can be explicitly tested
120+
with `((${#array[@]}))`, or the exit status of `_comp_compgen` that assigned
121+
values to the array can be used (when the generator is designed to return the
122+
appropriate exit status).
123+
114124
## Loop variable names
115125

116126
Use `i`, `j`, `k` for loop-local indices; `n` and `m` for lengths; some other

0 commit comments

Comments
 (0)