⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 arrays.html

📁 一本完整的描述Unix Shell 编程的工具书的所有范例
💻 HTML
📖 第 1 页 / 共 5 页
字号:
WIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/tip.png"HSPACE="5"ALT="Tip"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>The <BCLASS="COMMAND">array=( element1 element2 ... elementN )</B>	initialization operation, with the help of <AHREF="commandsub.html#COMMANDSUBREF">command substitution</A>, makes it	possible to load the contents of a text file into an array.</P><P>  	      <TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;   3&nbsp;filename=sample_file   4&nbsp;   5&nbsp;#            cat sample_file   6&nbsp;#   7&nbsp;#            1 a b c   8&nbsp;#            2 d e fg   9&nbsp;  10&nbsp;  11&nbsp;declare -a array1  12&nbsp;  13&nbsp;array1=( `cat "$filename"`)                #  Loads contents  14&nbsp;#         List file to stdout              #+ of $filename into array1.  15&nbsp;#  16&nbsp;#  array1=( `cat "$filename" | tr '\n' ' '`)  17&nbsp;#                            change linefeeds in file to spaces.   18&nbsp;#  Not necessary because Bash does word splitting,  19&nbsp;#+ changing linefeeds to spaces.  20&nbsp;  21&nbsp;echo ${array1[@]}            # List the array.  22&nbsp;#                              1 a b c 2 d e fg  23&nbsp;#  24&nbsp;#  Each whitespace-separated "word" in the file  25&nbsp;#+ has been assigned to an element of the array.  26&nbsp;  27&nbsp;element_count=${#array1[*]}  28&nbsp;echo $element_count          # 8</PRE></TD></TR></TABLE>      </P></TD></TR></TABLE></DIV><P>Clever scripting makes it possible to add array operations.</P><DIVCLASS="EXAMPLE"><HR><ANAME="ARRAYASSIGN"></A><P><B>Example 26-8. Initializing arrays</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#! /bin/bash   2&nbsp;# array-assign.bash   3&nbsp;   4&nbsp;#  Array operations are Bash specific,   5&nbsp;#+ hence the ".bash" in the script name.   6&nbsp;   7&nbsp;# Copyright (c) Michael S. Zick, 2003, All rights reserved.   8&nbsp;# License: Unrestricted reuse in any form, for any purpose.   9&nbsp;# Version: $ID$  10&nbsp;#  11&nbsp;# Clarification and additional comments by William Park.  12&nbsp;  13&nbsp;#  Based on an example provided by Stephane Chazelas  14&nbsp;#+ which appeared in the book: Advanced Bash Scripting Guide.  15&nbsp;  16&nbsp;# Output format of the 'times' command:  17&nbsp;# User CPU &#60;space&#62; System CPU  18&nbsp;# User CPU of dead children &#60;space&#62; System CPU of dead children  19&nbsp;  20&nbsp;#  Bash has two versions of assigning all elements of an array  21&nbsp;#+ to a new array variable.  22&nbsp;#  Both drop 'null reference' elements  23&nbsp;#+ in Bash versions 2.04, 2.05a and 2.05b.  24&nbsp;#  An additional array assignment that maintains the relationship of  25&nbsp;#+ [subscript]=value for arrays may be added to newer versions.  26&nbsp;  27&nbsp;#  Constructs a large array using an internal command,  28&nbsp;#+ but anything creating an array of several thousand elements  29&nbsp;#+ will do just fine.  30&nbsp;  31&nbsp;declare -a bigOne=( /dev/* )  32&nbsp;echo  33&nbsp;echo 'Conditions: Unquoted, default IFS, All-Elements-Of'  34&nbsp;echo "Number of elements in array is ${#bigOne[@]}"  35&nbsp;  36&nbsp;# set -vx  37&nbsp;  38&nbsp;  39&nbsp;  40&nbsp;echo  41&nbsp;echo '- - testing: =( ${array[@]} ) - -'  42&nbsp;times  43&nbsp;declare -a bigTwo=( ${bigOne[@]} )  44&nbsp;#                 ^              ^  45&nbsp;times  46&nbsp;  47&nbsp;echo  48&nbsp;echo '- - testing: =${array[@]} - -'  49&nbsp;times  50&nbsp;declare -a bigThree=${bigOne[@]}  51&nbsp;# No parentheses this time.  52&nbsp;times  53&nbsp;  54&nbsp;#  Comparing the numbers shows that the second form, pointed out  55&nbsp;#+ by Stephane Chazelas, is from three to four times faster.  56&nbsp;#  57&nbsp;#  William Park explains:  58&nbsp;#+ The bigTwo array assigned as single string, whereas  59&nbsp;#+ bigThree assigned element by element.  60&nbsp;#  So, in essence, you have:  61&nbsp;#                   bigTwo=( [0]="... ... ..." )  62&nbsp;#                   bigThree=( [0]="..." [1]="..." [2]="..." ... )  63&nbsp;  64&nbsp;  65&nbsp;#  I will continue to use the first form in my example descriptions  66&nbsp;#+ because I think it is a better illustration of what is happening.  67&nbsp;  68&nbsp;#  The reusable portions of my examples will actual contain  69&nbsp;#+ the second form where appropriate because of the speedup.  70&nbsp;  71&nbsp;# MSZ: Sorry about that earlier oversight folks.  72&nbsp;  73&nbsp;  74&nbsp;#  Note:  75&nbsp;#  ----  76&nbsp;#  The "declare -a" statements in lines 31 and 43  77&nbsp;#+ are not strictly necessary, since it is implicit  78&nbsp;#+ in the  Array=( ... )  assignment form.  79&nbsp;#  However, eliminating these declarations slows down  80&nbsp;#+ the execution of the following sections of the script.  81&nbsp;#  Try it, and see what happens.  82&nbsp;  83&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="NOTE"><TABLECLASS="NOTE"WIDTH="100%"BORDER="0"><TR><TDWIDTH="25"ALIGN="CENTER"VALIGN="TOP"><IMGSRC="common/note.png"HSPACE="5"ALT="Note"></TD><TDALIGN="LEFT"VALIGN="TOP"><P>Adding a superfluous <BCLASS="COMMAND">declare -a</B>	statement to an array declaration may speed up execution of	subsequent operations on the array.</P></TD></TR></TABLE></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="COPYARRAY"></A><P><B>Example 26-9. Copying and concatenating arrays</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#! /bin/bash   2&nbsp;# CopyArray.sh   3&nbsp;#   4&nbsp;# This script written by Michael Zick.   5&nbsp;# Used here with permission.   6&nbsp;   7&nbsp;#  How-To "Pass by Name &#38; Return by Name"   8&nbsp;#+ or "Building your own assignment statement".   9&nbsp;  10&nbsp;  11&nbsp;CpArray_Mac() {  12&nbsp;  13&nbsp;# Assignment Command Statement Builder  14&nbsp;  15&nbsp;    echo -n 'eval '  16&nbsp;    echo -n "$2"                    # Destination name  17&nbsp;    echo -n '=( ${'  18&nbsp;    echo -n "$1"                    # Source name  19&nbsp;    echo -n '[@]} )'  20&nbsp;  21&nbsp;# That could all be a single command.  22&nbsp;# Matter of style only.  23&nbsp;}  24&nbsp;  25&nbsp;declare -f CopyArray                # Function "Pointer"  26&nbsp;CopyArray=CpArray_Mac               # Statement Builder  27&nbsp;  28&nbsp;Hype()  29&nbsp;{  30&nbsp;  31&nbsp;# Hype the array named $1.  32&nbsp;# (Splice it together with array containing "Really Rocks".)  33&nbsp;# Return in array named $2.  34&nbsp;  35&nbsp;    local -a TMP  36&nbsp;    local -a hype=( Really Rocks )  37&nbsp;  38&nbsp;    $($CopyArray $1 TMP)  39&nbsp;    TMP=( ${TMP[@]} ${hype[@]} )  40&nbsp;    $($CopyArray TMP $2)  41&nbsp;}  42&nbsp;  43&nbsp;declare -a before=( Advanced Bash Scripting )  44&nbsp;declare -a after  45&nbsp;  46&nbsp;echo "Array Before = ${before[@]}"  47&nbsp;  48&nbsp;Hype before after  49&nbsp;  50&nbsp;echo "Array After = ${after[@]}"  51&nbsp;  52&nbsp;# Too much hype?  53&nbsp;  54&nbsp;echo "What ${after[@]:3:2}?"  55&nbsp;  56&nbsp;declare -a modest=( ${after[@]:2:1} ${after[@]:3:2} )  57&nbsp;#                    ---- substring extraction ----  58&nbsp;  59&nbsp;echo "Array Modest = ${modest[@]}"  60&nbsp;  61&nbsp;# What happened to 'before' ?  62&nbsp;  63&nbsp;echo "Array Before = ${before[@]}"  64&nbsp;  65&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><DIVCLASS="EXAMPLE"><HR><ANAME="ARRAYAPPEND"></A><P><B>Example 26-10. More on concatenating arrays</B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#! /bin/bash   2&nbsp;# array-append.bash   3&nbsp;   4&nbsp;# Copyright (c) Michael S. Zick, 2003, All rights reserved.   5&nbsp;# License: Unrestricted reuse in any form, for any purpose.   6&nbsp;# Version: $ID$   7&nbsp;#   8&nbsp;# Slightly modified in formatting by M.C.   9&nbsp;  10&nbsp;  11&nbsp;# Array operations are Bash-specific.  12&nbsp;# Legacy UNIX /bin/sh lacks equivalents.  13&nbsp;  14&nbsp;  15&nbsp;#  Pipe the output of this script to 'more'  16&nbsp;#+ so it doesn't scroll off the terminal.  17&nbsp;  18&nbsp;  19&nbsp;# Subscript packed.  20&nbsp;declare -a array1=( zero1 one1 two1 )  21&nbsp;# Subscript sparse ([1] is not defined).  22&nbsp;declare -a array2=( [0]=zero2 [2]=two2 [3]=three2 )  23&nbsp;  24&nbsp;echo  25&nbsp;echo '- Confirm that the array is really subscript sparse. -'  26&nbsp;echo "Number of elements: 4"        # Hard-coded for illustration.  27&nbsp;for (( i = 0 ; i &#60; 4 ; i++ ))  28&nbsp;do  29&nbsp;    echo "Element [$i]: ${array2[$i]}"  30&nbsp;done  31&nbsp;# See also the more general code example in basics-reviewed.bash.  32&nbsp;  33&nbsp;  34&nbsp;declare -a dest  35&nbsp;  36&nbsp;# Combine (append) two arrays into a third array.  37&nbsp;echo  38&nbsp;echo 'Conditions: Unquoted, default IFS, All-Elements-Of operator'  39&nbsp;echo '- Undefined elements not present, subscripts not maintained. -'  40&nbsp;# # The undefined elements do not exist; they are not being dropped.  41&nbsp;  42&nbsp;dest=( ${array1[@]} ${array2[@]} )  43&nbsp;# dest=${array1[@]}${array2[@]}     # Strange results, possibly a bug.  44&nbsp;  45&nbsp;# Now, list the result.  46&nbsp;echo  47&nbsp;echo '- - Testing Array Append - -'  48&nbsp;cnt=${#dest[@]}  49&nbsp;  50&nbsp;echo "Number of elements: $cnt"  51&nbsp;for (( i = 0 ; i &#60; cnt ; i++ ))  52&nbsp;do  53&nbsp;    echo "Element [$i]: ${dest[$i]}"  54&nbsp;done  55&nbsp;  56&nbsp;# Assign an array to a single array element (twice).  57&nbsp;dest[0]=${array1[@]}  58&nbsp;dest[1]=${array2[@]}  59&nbsp;  60&nbsp;# List the result.  61&nbsp;echo  62&nbsp;echo '- - Testing modified array - -'  63&nbsp;cnt=${#dest[@]}  64&nbsp;  65&nbsp;echo "Number of elements: $cnt"  66&nbsp;for (( i = 0 ; i &#60; cnt ; i++ ))  67&nbsp;do  68&nbsp;    echo "Element [$i]: ${dest[$i]}"  69&nbsp;done  70&nbsp;  71&nbsp;# Examine the modified second element.  72&nbsp;echo  73&nbsp;echo '- - Reassign and list second element - -'  74&nbsp;  75&nbsp;declare -a subArray=${dest[1]}  76&nbsp;cnt=${#subArray[@]}  77&nbsp;  78&nbsp;echo "Number of elements: $cnt"  79&nbsp;for (( i = 0 ; i &#60; cnt ; i++ ))  80&nbsp;do  81&nbsp;    echo "Element [$i]: ${subArray[$i]}"  82&nbsp;done  83&nbsp;  84&nbsp;#  The assignment of an entire array to a single element  85&nbsp;#+ of another array using the '=${ ... }' array assignment  86&nbsp;#+ has converted the array being assigned into a string,  87&nbsp;#+ with the elements separated by a space (the first character of IFS).  88&nbsp;  89&nbsp;# If the original elements didn't contain whitespace . . .  90&nbsp;# If the original array isn't subscript sparse . . .  91&nbsp;# Then we could get the original array structure back again.  92&nbsp;  93&nbsp;# Restore from the modified second element.  94&nbsp;echo  95&nbsp;echo '- - Listing restored element - -'  96&nbsp;  97&nbsp;declare -a subArray=( ${dest[1]} )  98&nbsp;cnt=${#subArray[@]}  99&nbsp; 100&nbsp;echo "Number of elements: $cnt" 101&nbsp;for (( i = 0 ; i &#60; cnt ; i++ )) 102&nbsp;do 103&nbsp;    echo "Element [$i]: ${subArray[$i]}" 104&nbsp;done 105&nbsp;echo '- - Do not depend on this behavior. - -' 106&nbsp;echo '- - This behavior is subject to change - -' 107&nbsp;echo '- - in versions of Bash newer than version 2.05b - -' 108&nbsp; 109&nbsp;# MSZ: Sorry about any earlier confusion folks. 110&nbsp; 111&nbsp;exit 0</PRE></TD></TR></TABLE><HR></DIV><P>--</P><P>Arrays permit deploying old familiar algorithms as shell scripts.        Whether this is necessarily a good idea is left to the reader to	decide.</P><DIVCLASS="EXAMPLE"><HR><ANAME="BUBBLE"></A><P><B>Example 26-11. An old friend:             <ICLASS="EMPHASIS">The Bubble Sort</I></B></P><TABLEBORDER="0"BGCOLOR="#E0E0E0"WIDTH="100%"><TR><TD><PRECLASS="PROGRAMLISTING">   1&nbsp;#!/bin/bash   2&nbsp;# bubble.sh: Bubble sort, of sorts.   3&nbsp;   4&nbsp;# Recall the algorithm for a bubble sort. In this particular version...

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -