bash-hackers-wiki/syntax/arrays/index.html

206 lines
81 KiB
HTML
Raw Normal View History

<!doctype html><html lang=en class=no-js> <head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><link href=https://flokoe.github.io/bash-hackers-wiki/syntax/arrays/ rel=canonical><link href=../arith_expr/ rel=prev><link href=../basicgrammar/ rel=next><link rel=icon href=../../assets/images/favicon.png><meta name=generator content="mkdocs-1.6.1, mkdocs-material-9.5.44"><title>Arrays - The Bash Hackers Wiki</title><link rel=stylesheet href=../../assets/stylesheets/main.0253249f.min.css><link rel=stylesheet href=../../assets/stylesheets/palette.06af60db.min.css><link rel=preconnect href=https://fonts.gstatic.com crossorigin><link rel=stylesheet href="https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,700,700i%7CRoboto+Mono:400,400i,700,700i&display=fallback"><style>:root{--md-text-font:"Roboto";--md-code-font:"Roboto Mono"}</style><script>__md_scope=new URL("../..",location),__md_hash=e=>[...e].reduce(((e,_)=>(e<<5)-e+_.charCodeAt(0)),0),__md_get=(e,_=localStorage,t=__md_scope)=>JSON.parse(_.getItem(t.pathname+"."+e)),__md_set=(e,_,t=localStorage,a=__md_scope)=>{try{t.setItem(a.pathname+"."+e,JSON.stringify(_))}catch(e){}}</script></head> <body dir=ltr data-md-color-scheme=default data-md-color-primary=indigo data-md-color-accent=indigo> <input class=md-toggle data-md-toggle=drawer type=checkbox id=__drawer autocomplete=off> <input class=md-toggle data-md-toggle=search type=checkbox id=__search autocomplete=off> <label class=md-overlay for=__drawer></label> <div data-md-component=skip> <a href=#arrays class=md-skip> Skip to content </a> </div> <div data-md-component=announce> </div> <header class=md-header data-md-component=header> <nav class="md-header__inner md-grid" aria-label=Header> <a href=../.. title="The Bash Hackers Wiki" class="md-header__button md-logo" aria-label="The Bash Hackers Wiki" data-md-component=logo> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 8a3 3 0 0 0 3-3 3 3 0 0 0-3-3 3 3 0 0 0-3 3 3 3 0 0 0 3 3m0 3.54C9.64 9.35 6.5 8 3 8v11c3.5 0 6.64 1.35 9 3.54 2.36-2.19 5.5-3.54 9-3.54V8c-3.5 0-6.64 1.35-9 3.54"/></svg> </a> <label class="md-header__button md-icon" for=__drawer> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M3 6h18v2H3zm0 5h18v2H3zm0 5h18v2H3z"/></svg> </label> <div class=md-header__title data-md-component=header-title> <div class=md-header__ellipsis> <div class=md-header__topic> <span class=md-ellipsis> The Bash Hackers Wiki </span> </div> <div class=md-header__topic data-md-component=header-topic> <span class=md-ellipsis> Arrays </span> </div> </div> </div> <form class=md-header__option data-md-component=palette> <input class=md-option data-md-color-media data-md-color-scheme=default data-md-color-primary=indigo data-md-color-accent=indigo aria-label="Switch to dark mode" type=radio name=__palette id=__palette_0> <label class="md-header__button md-icon" title="Switch to dark mode" for=__palette_1 hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 8a4 4 0 0 0-4 4 4 4 0 0 0 4 4 4 4 0 0 0 4-4 4 4 0 0 0-4-4m0 10a6 6 0 0 1-6-6 6 6 0 0 1 6-6 6 6 0 0 1 6 6 6 6 0 0 1-6 6m8-9.31V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12z"/></svg> </label> <input class=md-option data-md-color-media data-md-color-scheme=slate data-md-color-primary=indigo data-md-color-accent=indigo aria-label="Switch to light mode" type=radio name=__palette id=__palette_1> <label class="md-header__button md-icon" title="Switch to light mode" for=__palette_0 hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6a6 6 0 0 1 6 6 6 6 0 0 1-6 6m8-9.31V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12z"/></svg> </label> </form> <script>var palette=__md_get("__palette");if(palette&&palette.color){if("(prefers-color-scheme)"===palette.color.media){var media=matchMedia("(prefers-color-scheme: light)"),input=document.query
0: Peter
1: Anna
2: Greg
3: Jan
</code></pre></div> <p>Instead of using 4 separate variables, multiple related variables are grouped grouped together into <em>elements</em> of the array, accessible by their <em>key</em>. If you want the second name, ask for index 1 of the array <code>NAMES</code>.</p> <h2 id=indexing>Indexing<a class=headerlink href=#indexing title="Permanent link">&para;</a></h2> <p>Bash supports two different types of ksh-like one-dimensional arrays. <strong>Multidimensional arrays are not implemented</strong>.</p> <ul> <li><em>Indexed arrays</em> use positive integer numbers as keys. Indexed arrays are <strong>always sparse</strong>, meaning indexes are not necessarily contiguous. All syntax used for both assigning and dereferencing indexed arrays is an <a href=../arith_expr/ >arithmetic evaluation context</a> (see <a href=#Referencing>#Referencing</a>). As in C and many other languages, the numerical array indexes start at 0 (zero). Indexed arrays are the most common, useful, and portable type. Indexed arrays were first introduced to Bourne-like shells by ksh88. Similar, partially compatible syntax was inherited by many derivatives including Bash. Indexed arrays always carry the <code>-a</code> attribute.</li> <li><em>Associative arrays</em> (sometimes known as a "hash" or "dict") use arbitrary nonempty strings as keys. In other words, associative arrays allow you to look up a value from a table based upon its corresponding string label. <strong>Associative arrays are always unordered</strong>, they merely <em>associate</em> key-value pairs. If you retrieve multiple values from the array at once, you can't count on them coming out in the same order you put them in. Associative arrays always carry the <code>-A</code> attribute, and unlike indexed arrays, Bash requires that they always be declared explicitly (as indexed arrays are the default, see <a href=#Declaration>declaration</a>). Associative arrays were first introduced in ksh93, and similar mechanisms were later adopted by Zsh and Bash version 4. These three are currently the only POSIX-compatible shells with any associative array support.</li> </ul> <h2 id=syntax>Syntax<a class=headerlink href=#syntax title="Permanent link">&para;</a></h2> <h3 id=referencing>Referencing<a class=headerlink href=#referencing title="Permanent link">&para;</a></h3> <p>To accommodate referring to array variables and their individual elements, Bash extends the parameter naming scheme with a subscript suffix. Any valid ordinary scalar parameter name is also a valid array name: <code>[[:alpha:]_][[:alnum:]_]*</code>. The parameter name may be followed by an optional subscript enclosed in square brackets to refer to a member of the array.</p> <p>The overall syntax is <code>arrname[subscript]</code> - where for indexed arrays, <code>subscript</code> is any valid arithmetic expression, and for associative arrays, any nonempty string. Subscripts are first processed for parameter and arithmetic expansions, and command and process substitutions. When used within parameter expansions or as an argument to the <a href=../../commands/builtin/unset/ >unset</a> builtin, the special subscripts <code>*</code> and <code>@</code> are also accepted which act upon arrays analogously to the way the <code>@</code> and <code>*</code> special parameters act upon the positional parameters. In parsing the subscript, bash ignores any text that follows the closing bracket up to the end of the parameter name.</p> <p>With few exceptions, names of this form may be used anywhere ordinary parameter names are valid, such as within <a href=../arith_expr/ >arithmetic expressions</a>, <a href=../pe/ >parameter expansions</a>, and as arguments to builtins that accept parameter names. An <em>array</em> is a Bash parameter that has been given the <code>-a</code> (for indexed) or <code>-A</code> (for associative) <em>attributes</em>. However, any regular (non-special or positional) parameter may be validly referenced using a subscript, because in most contexts, referring to the zeroth element of an array is synonymous with referring to t
$ x=hi; printf &#39;%s &#39; &quot;$x&quot; &quot;${x[0]}&quot;; echo &quot;${_[0]}&quot;
hi hi hi
</code></pre></div> <p>The only exceptions to this rule are in a few cases where the array variable's name refers to the array as a whole. This is the case for the <code>unset</code> builtin (see <a href=#Destruction>destruction</a>) and when declaring an array without assigning any values (see <a href=#Declaration>declaration</a>).</p> <h3 id=declaration>Declaration<a class=headerlink href=#declaration title="Permanent link">&para;</a></h3> <p>The following explicitly give variables array attributes, making them arrays:</p> <table> <thead> <tr> <th>Syntax</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>ARRAY=()</code></td> <td>Declares an <strong>indexed</strong> array <code>ARRAY</code> and initializes it to be empty. This can also be used to empty an existing array.</td> </tr> <tr> <td><code>ARRAY[0]=</code></td> <td>Generally sets the first element of an <strong>indexed</strong> array. If no array <code>ARRAY</code> existed before, it is created.</td> </tr> <tr> <td><code>declare -a ARRAY</code></td> <td>Declares an <strong>indexed</strong> array <code>ARRAY</code>. An existing array is not initialized.</td> </tr> <tr> <td><code>declare -A ARRAY</code></td> <td>Declares an <strong>associative</strong> array <code>ARRAY</code>. This is the one and only way to create associative arrays.</td> </tr> </tbody> </table> <p>As an example, and for use below, let's declare our <code>NAMES</code> array as described <a href=#purpose>above</a>:</p> <div class=highlight><pre><span></span><code> declare -a NAMES=(&#39;Peter&#39; &#39;Anna&#39; &#39;Greg&#39; &#39;Jan&#39;)
</code></pre></div> <h3 id=storing-values>Storing values<a class=headerlink href=#storing-values title="Permanent link">&para;</a></h3> <p>Storing values in arrays is quite as simple as storing values in normal variables.</p> <table> <thead> <tr> <th>Syntax</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>ARRAY[N]=VALUE</code></td> <td>Sets the element <code>N</code> of the <strong>indexed</strong> array <code>ARRAY</code> to <code>VALUE</code>. <strong><code>N</code> can be any valid <a href=../arith_expr/ >arithmetic expression</a></strong>.</td> </tr> <tr> <td><code>ARRAY[STRING]=VALUE</code></td> <td>Sets the element indexed by <code>STRING</code> of the <strong>associative array</strong> <code>ARRAY</code>.</td> </tr> <tr> <td><code>ARRAY=VALUE</code></td> <td>As above. If no index is given, as a default the zeroth element is set to <code>VALUE</code>. Careful, this is even true of associative arrays - there is no error if no key is specified, and the value is assigned to string index "0".</td> </tr> <tr> <td><code>ARRAY=(E1\ E2\ ...)</code></td> <td>Compound array assignment - sets the whole array <code>ARRAY</code> to the given list of elements indexed sequentially starting at zero. The array is unset before assignment unless the += operator is used. When the list is empty (<code>ARRAY=()</code>), the array will be set to an empty array. This method obviously does not use explicit indexes. An <strong>associative array</strong> can <strong>not</strong> be set like that! Clearing an associative array using <code>ARRAY=()</code> works.</td> </tr> <tr> <td><code>ARRAY=([X]=E1\ [Y]=E2\ ...)</code></td> <td>Compound assignment for indexed arrays with index-value pairs declared individually (here for example <code>X</code> and <code>Y</code>). X and Y are arithmetic expressions. This syntax can be combined with the above - elements declared without an explicitly specified index are assigned sequentially starting at either the last element with an explicit index, or zero.</td> </tr> <tr> <td><code>ARRAY=([S1]=E1\ [S2]=E2\ ...)</code></td> <td>Individual mass-setting for <strong>associative arrays</strong>. The named indexes (here: <code>S1</code> and <code>S2</code>) are strings.</td> </tr> <tr> <td><code>ARRAY+=(E1\ E2\ ...)</code></td> <td>Append to ARRAY.</td> </tr> <tr> <td><code>ARRAY=("${ANOTHER_ARRAY[@]}")</code></td> <td>Copy ANOTHER_ARRAY to ARRAY, copying each element.</td> </tr> </tbody> </table> <p>As of now, arrays can't be exported.</p> <h3 id=getting-values>Getting values<a class=headerlink href=#getting-values title="Permanent link">&para;</a></h3> <div class="admonition info"> <p>For completeness and details on several parameter expansion variants, see the <a href=../pe/ >article about parameter expansion</a> and check the notes about arrays.</p> </div> <table> <thead> <tr> <th>Syntax</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><code>${ARRAY[N]}</code></td> <td>Expands to the value of the index <code>N</code> in the <strong>indexed</strong> array <code>ARRAY</code>. If <code>N</code> is a negative number, it's treated as the offset from the maximum assigned index (can't be used for assignment) - 1</td> </tr> <tr> <td><code>${ARRAY[S]}</code></td> <td>Expands to the value of the index <code>S</code> in the <strong>associative</strong> array <code>ARRAY</code>.</td> </tr> <tr> <td><code>"${ARRAY[@]}" ${ARRAY[@]} "${ARRAY[*]}" ${ARRAY[*]}</code></td> <td>Similar to <a href=../../scripting/posparams/#mass_usage>mass-expanding positional parameters</a>, this expands to all elements. If unquoted, both subscripts <code>*</code> and <code>@</code> expand to the same result, if quoted, <code>@</code> expands to all elements individually quoted, <code>*</code> expands to all elements quoted as a whole.</td> </tr> <tr> <td><code>"${ARRAY[@]:N:M}" ${ARRAY[@]:N:M} "${ARRAY[*]:N:M}" ${ARRAY[*]:N:M}</code></td> <td>Similar to what this syntax does for the characters of a single string when doing <a href=../pe/#substring_expansion>substring expansion</a>, this expands to <code>M</code> eleme
</code></pre></div> <p>then pathname expansion will expand to the filename <code>x1</code> and break your processing!</p> <p>Even worse, if <code>nullglob</code> is set, your array/index will disappear.</p> <p>To avoid this, <strong>always quote</strong> the array name and index:</p> <div class=highlight><pre><span></span><code>unset -v &#39;x[1]&#39;
</code></pre></div> <p>This applies generally to all commands which take variable names as arguments. Single quotes preferred.</p> </div> <h2 id=usage>Usage<a class=headerlink href=#usage title="Permanent link">&para;</a></h2> <h3 id=numerical-index>Numerical Index<a class=headerlink href=#numerical-index title="Permanent link">&para;</a></h3> <p>Numerical indexed arrays are easy to understand and easy to use. The <a href=#purpose>Purpose</a> and <a href=#indexing>Indexing</a> chapters above more or less explain all the needed background theory.</p> <p>Now, some examples and comments for you.</p> <p>Let's say we have an array <code>sentence</code> which is initialized as follows:</p> <div class=highlight><pre><span></span><code>sentence=(Be liberal in what you accept, and conservative in what you send)
</code></pre></div> <p>Since no special code is there to prevent word splitting (no quotes), every word there will be assigned to an individual array element. When you count the words you see, you should get 12. Now let's see if Bash has the same opinion:</p> <div class=highlight><pre><span></span><code>$ echo ${#sentence[@]}
12
</code></pre></div> <p>Yes, 12. Fine. You can take this number to walk through the array. Just <strong>subtract 1 from the number of elements, and start your walk at 0 (zero)</strong>:</p> <div class=highlight><pre><span></span><code>((n_elements=${#sentence[@]}, max_index=n_elements - 1))
for ((i = 0; i &lt;= max_index; i++)); do
echo &quot;Element $i: &#39;${sentence[i]}&#39;&quot;
done
</code></pre></div> <p>You always have to remember that, it seems newbies have problems sometimes. Please understand that <strong>numerical array indexing begins at 0 (zero)</strong>!</p> <p>The method above, walking through an array by just knowing its number of elements, only works for arrays where all elements are set, of course. If one element in the middle is removed, then the calculation is nonsense, because the number of elements doesn't correspond to the highest used index anymore (we call them "<em>sparse arrays</em>").</p> <p>Now, suppose that you want to replace your array <code>sentence</code> with the values in the <a href=#purpose>previously-declared array</a> <code>NAMES</code> . You might think you could just do</p> <div class=highlight><pre><span></span><code>$ unset sentence ; declare -a sentence=NAMES
$ echo ${#sentence[@]}
1
# omit calculating max_index as above, and iterate as one-liner
$ for ((i = 0; i &lt; ${#sentence[@]}; i++)); do echo &quot;Element $i: &#39;${sentence[i]}&#39;&quot; ; done
Element 0: &#39;NAMES&#39;
</code></pre></div> <p>Obviously that's wrong. What about</p> <div class=highlight><pre><span></span><code>$ unset sentence ; declare -a sentence=${NAMES}
</code></pre></div> <p>? Again, wrong:</p> <div class=highlight><pre><span></span><code>$ echo ${#sentence[*]}
1
$ for ((i = 0; i &lt; ${#sentence[@]}; i++)); do echo &quot;Element $i: &#39;${sentence[i]}&#39;&quot; ; done
Element 0: &#39;Peter&#39;
</code></pre></div> <p>So what's the <strong>right</strong> way? The (slightly ugly) answer is, reuse the enumeration syntax:</p> <div class=highlight><pre><span></span><code>$ unset sentence ; declare -a sentence=(&quot;${NAMES[@]}&quot;)
$ echo ${#sentence[@]}
4
$ for ((i = 0; i &lt; ${#sentence[@]}; i++)); do echo &quot;Element $i: &#39;${sentence[i]}&#39;&quot; ; done
Element 0: &#39;Peter&#39;
Element 1: &#39;Anna&#39;
Element 2: &#39;Greg&#39;
Element 3: &#39;Jan&#39;
</code></pre></div> <h3 id=associative-bash-4>Associative (Bash 4)<a class=headerlink href=#associative-bash-4 title="Permanent link">&para;</a></h3> <p>Associative arrays (or <em>hash tables</em>) are not much more complicated than numerical indexed arrays. The numerical index value (in Bash a number starting at zero) just is replaced with an arbitrary string:</p> <div class=highlight><pre><span></span><code># declare -A, introduced with Bash 4 to declare an associative array
declare -A sentence
sentence[Begin]=&#39;Be liberal in what&#39;
sentence[Middle]=&#39;you accept, and conservative&#39;
sentence[End]=&#39;in what you send&#39;
sentence[&#39;Very end&#39;]=...
</code></pre></div> <p><u><strong>Beware:</strong></u> don't rely on the fact that the elements are ordered in memory like they were declared, it could look like this:</p> <div class=highlight><pre><span></span><code># output from &#39;set&#39; command
sentence=([End]=&quot;in what you send&quot; [Middle]=&quot;you accept, and conservative &quot; [Begin]=&quot;Be liberal in what &quot; [&quot;Very end&quot;]=&quot;...&quot;)
</code></pre></div> <p>This effectively means, you can get the data back with <code>"${sentence[@]}"</code>, of course (just like with numerical indexing), but you can't rely on a specific order. If you want to store ordered data, or re-order data, go with numerical indexes. For associative arrays, you usually query known index values:</p> <div class=highlight><pre><span></span><code>for element in Begin Middle End &quot;Very end&quot;; do
printf &quot;%s&quot; &quot;${sentence[$element]}&quot;
done
printf &quot;\n&quot;
</code></pre></div> <p><strong>A nice code example:</strong> Checking for duplicate files using an associative array indexed with the SHA sum of the files:</p> <div class=highlight><pre><span></span><code># Thanks to Tramp in #bash for the idea and the code
unset flist; declare -A flist;
while read -r sum fname; do
if [[ ${flist[$sum]} ]]; then
printf &#39;rm -- &quot;%s&quot; # Same as &gt;%s&lt;\n&#39; &quot;$fname&quot; &quot;${flist[$sum]}&quot;
else
flist[$sum]=&quot;$fname&quot;
fi
done &lt; &lt;(find . -type f -exec sha256sum {} +) &gt;rmdups
</code></pre></div> <h3 id=integer-arrays>Integer arrays<a class=headerlink href=#integer-arrays title="Permanent link">&para;</a></h3> <p>Any type attributes applied to an array apply to all elements of the array. If the integer attribute is set for either indexed or associative arrays, then values are considered as arithmetic for both compound and ordinary assignment, and the += operator is modified in the same way as for ordinary integer variables.</p> <div class=highlight><pre><span></span><code> ~ $ ( declare -ia &#39;a=(2+4 [2]=2+2 [a[2]]=&quot;a[2]&quot;)&#39; &#39;a+=(42 [a[4]]+=3)&#39;; declare -p a )
declare -ai a=&#39;([0]=&quot;6&quot; [2]=&quot;4&quot; [4]=&quot;7&quot; [5]=&quot;42&quot;)&#39;
</code></pre></div> <p><code>a[0]</code> is assigned to the result of <code>2+4</code>. <code>a[2]</code> gets the result of <code>2+2</code>. The last index in the first assignment is the result of <code>a[2]</code>, which has already been assigned as <code>4</code>, and its value is also given <code>a[2]</code>.</p> <p>This shows that even though any existing arrays named <code>a</code> in the current scope have already been unset by using <code>=</code> instead of <code>+=</code> to the compound assignment, arithmetic variables within keys can self-reference any elements already assigned within the same compound-assignment. With integer arrays this also applies to expressions to the right of the <code>=</code>. (See <a href=#evaluation_order>evaluation order</a>, the right side of an arithmetic assignment is typically evaluated first in Bash.)</p> <p>The second compound assignment argument to declare uses <code>+=</code>, so it appends after the last element of the existing array rather than deleting it and creating a new array, so <code>a[5]</code> gets <code>42</code>.</p> <p>Lastly, the element whose index is the value of <code>a[4]</code> (<code>4</code>), gets <code>3</code> added to its existing value, making <code>a[4]</code> == <code>7</code>. Note that having the integer attribute set this time causes += to add, rather than append a string, as it would for a non-integer array.</p> <p>The single quotes force the assignments to be evaluated in the environment of <code>declare</code>. This is important because attributes are only applied to the assignment after assignment arguments are processed. Without them the <code>+=</code> compound assignment would have been invalid, and strings would have been inserted into the integer array without evaluating the arithmetic. A special-case of this is shown in the next section.</p> <div class="admonition info"> <p class=admonition-title>info</p> <p>Bash declaration commands are really keywords in disguise. They magically parse arguments to determine whether they are in the form of a valid assignment. If so, they are evaluated as assignments. If not, they are undergo normal argument expansion before being passed to the builtin which evaluates the resulting string as an assignment (somewhat like <code>eval</code>, but there are differences.) <code>'Todo:</code>\' Discuss this in detail.</p> </div> <h3 id=indirection>Indirection<a class=headerlink href=#indirection title="Permanent link">&para;</a></h3> <p>Arrays can be expanded indirectly using the indirect parameter expansion syntax. Parameters whose values are of the form: <code>name[index]</code>, <code>name[@]</code>, or <code>name[*]</code> when expanded indirectly produce the expected results. This is mainly useful for passing arrays (especially multiple arrays) by name to a function.</p> <p>This example is an "isSubset"-like predicate which returns true if all key-value pairs of the array given as the first argument to isSubset correspond to a key-value of the array given as the second argument. It demonstrates both indirect array expansion and indirect key-passing without eval using the aforementioned special compound assignment expansion.</p> <div class=highlight><pre><span></span><code>isSubset() {
local -a &#39;xkeys=(&quot;${!&#39;&quot;$1&quot;&#39;[@]}&quot;)&#39; &#39;ykeys=(&quot;${!&#39;&quot;$2&quot;&#39;[@]}&quot;)&#39;
set -- &quot;${@/%/[key]}&quot;
(( ${#xkeys[@]} &lt;= ${#ykeys[@]} )) || return 1
local key
for key in &quot;${xkeys[@]}&quot;; do
[[ ${!2+_} &amp;&amp; ${!1} == ${!2} ]] || return 1
done
}
main() {
# &quot;a&quot; is a subset of &quot;b&quot;
local -a &#39;a=({0..5})&#39; &#39;b=({0..10})&#39;
isSubset a b
echo $? # true
# &quot;a&quot; contains a key not in &quot;b&quot;
local -a &#39;a=([5]=5 {6..11})&#39; &#39;b=({0..10})&#39;
isSubset a b
echo $? # false
# &quot;a&quot; contains an element whose value != the corresponding member of &quot;b&quot;
local -a &#39;a=([5]=5 6 8 9 10)&#39; &#39;b=({0..10})&#39;
isSubset a b
echo $? # false
}
main
</code></pre></div> <p>This script is one way of implementing a crude multidimensional associative array by storing array definitions in an array and referencing them through indirection. The script takes two keys and dynamically calls a function whose name is resolved from the array.</p> <div class=highlight><pre><span></span><code>callFuncs() {
# Set up indirect references as positional parameters to minimize local name collisions.
set -- &quot;${@:1:3}&quot; ${2+&#39;a[&quot;$1&quot;]&#39; &quot;$1&quot;&#39;[&quot;$2&quot;]&#39;}
# The only way to test for set but null parameters is unfortunately to test each individually.
local x
for x; do
[[ $x ]] || return 0
done
local -A a=(
[foo]=&#39;([r]=f [s]=g [t]=h)&#39;
[bar]=&#39;([u]=i [v]=j [w]=k)&#39;
[baz]=&#39;([x]=l [y]=m [z]=n)&#39;
) ${4+${a[&quot;$1&quot;]+&quot;${1}=${!3}&quot;}} # For example, if &quot;$1&quot; is &quot;bar&quot; then define a new array: bar=([u]=i [v]=j [w]=k)
${4+${a[&quot;$1&quot;]+&quot;${!4-:}&quot;}} # Now just lookup the new array. for inputs: &quot;bar&quot; &quot;v&quot;, the function named &quot;j&quot; will be called, which prints &quot;j&quot; to stdout.
}
main() {
# Define functions named {f..n} which just print their own names.
local fun=&#39;() { echo &quot;$FUNCNAME&quot;; }&#39; x
for x in {f..n}; do
eval &quot;${x}${fun}&quot;
done
callFuncs &quot;$@&quot;
}
main &quot;$@&quot;
</code></pre></div> <h2 id=bugs-and-portability-considerations>Bugs and Portability Considerations<a class=headerlink href=#bugs-and-portability-considerations title="Permanent link">&para;</a></h2> <ul> <li>Arrays are not specified by POSIX. One-dimensional indexed arrays are supported using similar syntax and semantics by most Korn-like shells.</li> <li>Associative arrays are supported via <code>typeset -A</code> in Bash 4, Zsh, and Ksh93.</li> <li>In Ksh93, arrays whose types are not given explicitly are not necessarily indexed. Arrays defined using compound assignments which specify subscripts are associative by default. In Bash, associative arrays can <em>only</em> be created by explicitly declaring them as associative, otherwise they are always indexed. In addition, ksh93 has several other compound structures whose types can be determined by the compound assignment syntax used to create them.</li> <li>In Ksh93, using the <code>=</code> compound assignment operator unsets the array, including any attributes that have been set on the array prior to assignment. In order to preserve attributes, you must use the <code>+=</code> operator. However, declaring an associative array, then attempting an <code>a=(...)</code> style compound assignment without specifying indexes is an error. I can't explain this inconsistency.<code>$ ksh -c 'function f { typeset -a a; a=([0]=foo [1]=bar); typeset -p a; }; f' # Attribute is lost, and since subscripts are given, we default to associative. typeset -A a=([0]=foo [1]=bar) $ ksh -c 'function f { typeset -a a; a+=([0]=foo [1]=bar); typeset -p a; }; f' # Now using += gives us the expected results. typeset -a a=(foo bar) $ ksh -c 'function f { typeset -A a; a=(foo bar); typeset -p a; }; f' # On top of that, the reverse does NOT unset the attribute. No idea why. ksh: f: line 1: cannot append index array to associative array a</code></li> <li>Only Bash and mksh support compound assignment with mixed explicit subscripts and automatically incrementing subscripts. In ksh93, in order to specify individual subscripts within a compound assignment, all subscripts must be given (or none). Zsh doesn't support specifying individual subscripts at all.</li> <li>Appending to a compound assignment is a fairly portable way to append elements after the last index of an array. In Bash, this also sets append mode for all individual assignments within the compound assignment, such that if a lower subscript is specified, subsequent elements will be appended to previous values. In ksh93, it causes subscripts to be ignored, forcing appending everything after the last element. (Appending has different meaning due to support for multi-dimensional arrays and nested compound datastructures.) <code>$ ksh -c 'function f { typeset -a a; a+=(foo bar baz); a+=([3]=blah [0]=bork [1]=blarg [2]=zooj); typeset -p a; }; f' # ksh93 forces appending to the array, disregarding subscripts typeset -a a=(foo bar baz '[3]=blah' '[0]=bork' '[1]=blarg' '[2]=zooj') $ bash -c 'function f { typeset -a a; a+=(foo bar baz); a+=(blah [0]=bork blarg zooj); typeset -p a; }; f' # Bash applies += to every individual subscript. declare -a a='([0]="foobork" [1]="barblarg" [2]="bazzooj" [3]="blah")' $ mksh -c 'function f { typeset -a a; a+=(foo bar baz); a+=(blah [0]=bork blarg zooj); typeset -p a; }; f' # Mksh does like Bash, but clobbers previous values rather than appending. set -A a typeset a[0]=bork typeset a[1]=blarg typeset a[2]=zooj typeset a[3]=blah</code></li> <li>In Bash and Zsh, the alternate value assignment parameter expansion (<code>${arr[idx]:=foo}</code>) evaluates the subscript twice, first to determine whether to expand the alternate, and second to determine the index to assign the alternate to. See <a href=#evaluation_order>evaluation order</a>. <code>$ : ${_[$(echo $RANDOM &gt;&amp;2)1]:=$(echo hi &gt;&amp;2)} 13574 hi 14485</code></li> <li>In Zsh, arrays are indexed starting at 1 in its default mode. Emulation modes are required in order to get any kind of portability.</li> <li>Zsh and mksh do not support compound assignment
contexts. Each context is tested for expansions (represented by digits) and
arithmetic (letters), ordered from left to right within the expression. The
output corresponds to the way evaluation is re-ordered for each shell:
a[ $1 a ]=${b[ $2 b ]:=${c[ $3 c ]}} No attributes
a[ $1 a ]=${b[ $2 b ]:=c[ $3 c ]} typeset -ia a
a[ $1 a ]=${b[ $2 b ]:=c[ $3 c ]} typeset -ia b
a[ $1 a ]=${b[ $2 b ]:=c[ $3 c ]} typeset -ia a b
(( a[ $1 a ] = b[ $2 b ] ${c[ $3 c ]} )) No attributes
(( a[ $1 a ] = ${b[ $2 b ]:=c[ $3 c ]} )) typeset -ia b
a+=( [ $1 a ]=${b[ $2 b ]:=${c[ $3 c ]}} [ $4 d ]=$(( $5 e )) ) typeset -a a
a+=( [ $1 a ]=${b[ $2 b ]:=c[ $3 c ]} [ $4 d ]=${5}e ) typeset -ia a
bash: 4.2.42(1)-release
2 b 3 c 2 b 1 a
2 b 3 2 b 1 a c
2 b 3 2 b c 1 a
2 b 3 2 b c 1 a c
1 2 3 c b a
1 2 b 3 2 b c c a
1 2 b 3 c 2 b 4 5 e a d
1 2 b 3 2 b 4 5 a c d e
ksh93: Version AJM 93v- 2013-02-22
1 2 b b a
1 2 b b a
1 2 b b a
1 2 b b a
1 2 3 c b a
1 2 b b a
1 2 b b a 4 5 e d
1 2 b b a 4 5 d e
mksh: @(#)MIRBSD KSH R44 2013/02/24
2 b 3 c 1 a
2 b 3 1 a c
2 b 3 c 1 a
2 b 3 c 1 a
1 2 3 c a b
1 2 b 3 c a
1 2 b 3 c 4 5 e a d
1 2 b 3 4 5 a c d e
zsh: 5.0.2
2 b 3 c 2 b 1 a
2 b 3 2 b 1 a c
2 b 1 a
2 b 1 a
1 2 3 c b a
1 2 b a
1 2 b 3 c 2 b 4 5 e
1 2 b 3 2 b 4 5
</code></pre></div> <h2 id=see-also>See also<a class=headerlink href=#see-also title="Permanent link">&para;</a></h2> <ul> <li><a href=../pe/ >Parameter expansion</a> (contains sections for arrays)</li> <li><a href=../ccmd/classic_for/ >classic_for</a> (contains some examples to iterate over arrays)</li> <li><a href=../../commands/builtin/declare/ >declare</a></li> <li><a href=http://mywiki.wooledge.org/BashFAQ/005>BashFAQ 005 - How can I use array variables?</a> - A very detailed discussion on arrays with many examples.</li> <li><a href=http://mywiki.wooledge.org/BashSheet#Arrays>BashSheet - Arrays</a> - Bashsheet quick-reference on Greycat's wiki.</li> </ul> <aside class=md-source-file> <span class=md-source-file__fact> <span class=md-icon title="Last update"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M21 13.1c-.1 0-.3.1-.4.2l-1 1 2.1 2.1 1-1c.2-.2.2-.6 0-.8l-1.3-1.3c-.1-.1-.2-.2-.4-.2m-1.9 1.8-6.1 6V23h2.1l6.1-6.1zM12.5 7v5.2l4 2.4-1 1L11 13V7zM11 21.9c-5.1-.5-9-4.8-9-9.9C2 6.5 6.5 2 12 2c5.3 0 9.6 4.1 10 9.3-.3-.1-.6-.2-1-.2s-.7.1-1 .2C19.6 7.2 16.2 4 12 4c-4.4 0-8 3.6-8 8 0 4.1 3.1 7.5 7.1 7.9l-.1.2z"/></svg> </span> <span class="git-revision-date-localized-plugin git-revision-date-localized-plugin-date">November 13, 2024</span> </span> <span class=md-source-file__fact> <span class=md-icon title=Created> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M14.47 15.08 11 13V7h1.5v5.25l3.08 1.83c-.41.28-.79.62-1.11 1m-1.39 4.84c-.36.05-.71.08-1.08.08-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8c0 .37-.03.72-.08 1.08.69.1 1.33.32 1.92.64.1-.56.16-1.13.16-1.72 0-5.5-4.5-10-10-10S2 6.5 2 12s4.47 10 10 10c.59 0 1.16-.06 1.72-.16-.32-.59-.54-1.23-.64-1.92M18 15v3h-3v2h3v3h2v-3h3v-2h-3v-3z"/></svg> </span> <span class="git-revision-date-localized-plugin git-revision-date-localized-plugin-date">November 13, 2024</span> </span> </aside> <h2 id=__comments>Comments</h2> <script src=https://giscus.app/client.js data-repo=flokoe/bash-hackers-wiki data-repo-id=R_kgDOJ3Nr6Q data-category="Giscus Page Comments" data-category-id=DIC_kwDOJ3Nr6c4CXq9t data-mapping=pathname data-strict=1 data-reactions-enabled=1 data-emit-metadata=0 data-input-position=top data-theme=preferred_color_scheme data-lang=en data-loading=lazy crossorigin=anonymous async>
</script> <script>
var giscus = document.querySelector("script[src*=giscus]")
/* Set palette on initial load */
var palette = __md_get("__palette")
if (palette && typeof palette.color === "object") {
var theme = palette.color.scheme === "slate" ? "dark" : "light"
giscus.setAttribute("data-theme", theme)
}
/* Register event handlers after documented loaded */
document.addEventListener("DOMContentLoaded", function() {
var ref = document.querySelector("[data-md-component=palette]")
ref.addEventListener("change", function() {
var palette = __md_get("__palette")
if (palette && typeof palette.color === "object") {
var theme = palette.color.scheme === "slate" ? "dark" : "light"
/* Instruct Giscus to change theme */
var frame = document.querySelector(".giscus-frame")
frame.contentWindow.postMessage(
{ giscus: { setConfig: { theme } } },
"https://giscus.app"
)
}
})
})
</script> </article> </div> <script>var target=document.getElementById(location.hash.slice(1));target&&target.name&&(target.checked=target.name.startsWith("__tabbed_"))</script> </div> <button type=button class="md-top md-icon" data-md-component=top hidden> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M13 20h-2V8l-5.5 5.5-1.42-1.42L12 4.16l7.92 7.92-1.42 1.42L13 8z"/></svg> Back to top </button> </main> <footer class=md-footer> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class=md-copyright> Made with <a href=https://squidfunk.github.io/mkdocs-material/ target=_blank rel=noopener> Material for MkDocs </a> </div> </div> </div> </footer> </div> <div class=md-dialog data-md-component=dialog> <div class="md-dialog__inner md-typeset"></div> </div> <script id=__config type=application/json>{"base": "../..", "features": ["navigation.instant", "navigation.tracking", "navigation.tabs", "navigation.sections", "navigation.top", "content.action.view", "content.action.edit", "search.suggest", "search.highlight", "content.code.copy"], "search": "../../assets/javascripts/workers/search.6ce7567c.min.js", "translations": {"clipboard.copied": "Copied to clipboard", "clipboard.copy": "Copy to clipboard", "search.result.more.one": "1 more on this page", "search.result.more.other": "# more on this page", "search.result.none": "No matching documents", "search.result.one": "1 matching document", "search.result.other": "# matching documents", "search.result.placeholder": "Type to start searching", "search.result.term.missing": "Missing", "select.version": "Select version"}}</script> <script src=../../assets/javascripts/bundle.83f73b43.min.js></script> </body> </html>