-
Notifications
You must be signed in to change notification settings - Fork 0
/
arrays.html
2221 lines (1826 loc) · 54.4 KB
/
arrays.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Arrays</title>
<meta name="GENERATOR" content="Modular DocBook HTML Stylesheet Version 1.7">
<link rel="HOME" title="Advanced Bash-Scripting Guide" href="./index.html">
<link rel="UP" title="Advanced Topics" href="./part5.html">
<link rel="PREVIOUS" title="List Constructs" href="./list-cons.html">
<link rel="NEXT" title="Indirect References" href="./ivr.html">
</head>
<body class="CHAPTER" bgcolor="#FFFFFF" alink="#0000FF" link="#0000FF" text="#000000" vlink="#840084">
<div id="dic_bubble" class="selection_bubble fontSize13 noSelect" style="z-index:9999; border: 1px solid #4AAEDE;fetching=false">
</div>
<div class="NAVHEADER">
<table summary="Header navigation table" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<th colspan="3" align="center">Advanced Bash-Scripting Guide: </th>
</tr>
<tr>
<td align="left" valign="bottom" width="10%">
<a href="./list-cons.html" accesskey="P">이전</a>
</td>
<td align="center" valign="bottom" width="80%">
</td>
<td align="right" valign="bottom" width="10%">
<a href="./ivr.html" accesskey="N">다음</a>
</td>
</tr>
</tbody>
</table>
<hr align="LEFT" width="100%">
</div>
<div class="CHAPTER">
<h1>
<a name="ARRAYS">
</a>27장. 배열</h1>
<p>
<a name="ARRAYREF">
</a>
</p>
<p>Bash 의 새버전은 1차원 배열을 지원합니다.
<a name="BRACKARRAY">
</a>
배열의 요소들은
<tt class="USERINPUT">
<b>variable[xx]</b>
</tt> 처럼 선언되어질 수 있습니다. 대신에, 스크립트는 전체 배열을
<tt class="USERINPUT">
<b>declare -a variable</b>
</tt> 문으로 직접 지정해 줄 수도 있습니다. 배열 요소를 역참조하려면 (내용을 알아내려면)
<tt class="USERINPUT">
<b>${element[xx]}</b>
</tt> 처럼
<i class="FIRSTTERM">중괄호</i> 표기를 쓰면 됩니다.
</p>
<p>
<a name="ARRAYNOTATION">
</a>
</p>
<div class="EXAMPLE">
<a name="EX66">
</a>
<p>
<b>예제 27-1. 간단한 배열 사용법</b>
</p>
<table bgcolor="#E0E0E0" border="0" width="100%">
<tbody>
<tr>
<td>
<font color="#000000">
<pre class="PROGRAMLISTING">#!/bin/bash
area[11]=23
area[13]=37
area[51]=UFOs
# Array members need not be consecutive or contiguous.
# Some members of the array can be left uninitialized.
# Gaps in the array are okay.
# In fact, arrays with sparse data ("sparse arrays")
#+ are useful in spreadsheet-processing software.
echo -n "area[11] = "
echo ${area[11]} # {curly brackets} needed.
echo -n "area[13] = "
echo ${area[13]}
echo "Contents of area[51] are ${area[51]}."
# Contents of uninitialized array variable print blank (null variable).
echo -n "area[43] = "
echo ${area[43]}
echo "(area[43] unassigned)"
echo
# Sum of two array variables assigned to third
area[5]=`expr ${area[11]} + ${area[13]}`
echo "area[5] = area[11] + area[13]"
echo -n "area[5] = "
echo ${area[5]}
area[6]=`expr ${area[11]} + ${area[51]}`
echo "area[6] = area[11] + area[51]"
echo -n "area[6] = "
echo ${area[6]}
# This fails because adding an integer to a string is not permitted.
echo; echo; echo
# -----------------------------------------------------------------
# Another array, "area2".
# Another way of assigning array variables...
# array_name=( XXX YYY ZZZ ... )
area2=( zero one two three four )
echo -n "area2[0] = "
echo ${area2[0]}
# Aha, zero-based indexing (first element of array is [0], not [1]).
echo -n "area2[1] = "
echo ${area2[1]} # [1] is second element of array.
# -----------------------------------------------------------------
echo; echo; echo
# -----------------------------------------------
# Yet another array, "area3".
# Yet another way of assigning array variables...
# array_name=([xx]=XXX [yy]=YYY ...)
area3=([17]=seventeen [24]=twenty-four)
echo -n "area3[17] = "
echo ${area3[17]}
echo -n "area3[24] = "
echo ${area3[24]}
# -----------------------------------------------
exit 0</pre>
</font>
</td>
</tr>
</tbody>
</table>
</div>
<p>
<a name="ARRAYINIT0">
</a>
</p>
<p>위에서 볼 수 있듯이, 배열 전체를 초기화하는 편한 방법은
<tt class="VARNAME">array=( element1 element2 ... elementN )</tt> 를 쓰는 것입니다.
</p>
<p>
<table bgcolor="#E0E0E0" border="0" width="100%">
<tbody>
<tr>
<td>
<font color="#000000">
<pre class="PROGRAMLISTING">base64_charset=( {A..Z} {a..z} {0..9} + / = )
# Using extended brace expansion
#+ to initialize the elements of the array.
# Excerpted from vladz's "base64.sh" script
#+ in the "Contributed Scripts" appendix.</pre>
</font>
</td>
</tr>
</tbody>
</table>
</p>
<p>
<a name="ARRAYOPSVARS">
</a>
</p>
<table class="SIDEBAR" border="1" cellpadding="5">
<tbody>
<tr>
<td>
<div class="SIDEBAR">
<a name="AEN18812">
</a>
<p>
</p>
<p>Bash 에서는, 변수가 적확하게 배열로 선언되지 않았다고 하더라도, 변수에 배열
연산을 할 수 있습니다.
</p>
<p>
<table bgcolor="#E0E0E0" border="0" width="100%">
<tbody>
<tr>
<td>
<font color="#000000">
<pre class="PROGRAMLISTING">string=abcABC123ABCabc
echo ${string[@]} # abcABC123ABCabc
echo ${string[*]} # abcABC123ABCabc
echo ${string[0]} # abcABC123ABCabc
echo ${string[1]} # No output!
# Why?
echo ${#string[@]} # 1
# One element in the array.
# The string itself.
# Thank you, Michael Zick, for pointing this out.</pre>
</font>
</td>
</tr>
</tbody>
</table>
<a href="./untyped.html#BVUNTYPED">Bash variables are untyped</a> 에 다시 한번 언급됩니다.
</p>
<p>
</p>
</div>
</td>
</tr>
</tbody>
</table>
<div class="EXAMPLE">
<a name="POEM">
</a>
<p>
<b>예제 27-2. 시 출력하기</b>
</p>
<table bgcolor="#E0E0E0" border="0" width="100%">
<tbody>
<tr>
<td>
<font color="#000000">
<pre class="PROGRAMLISTING">#!/bin/bash
# poem.sh: Pretty-prints one of the ABS Guide author's favorite poems.
# Lines of the poem (single stanza).
Line[1]="I do not know which to prefer,"
Line[2]="The beauty of inflections"
Line[3]="Or the beauty of innuendoes,"
Line[4]="The blackbird whistling"
Line[5]="Or just after."
# Note that quoting permits embedding whitespace.
# Attribution.
Attrib[1]=" Wallace Stevens"
Attrib[2]="\"Thirteen Ways of Looking at a Blackbird\""
# This poem is in the Public Domain (copyright expired).
echo
tput bold # Bold print.
for index in 1 2 3 4 5 # Five lines.
do
printf " %s\n" "${Line[index]}"
done
for index in 1 2 # Two attribution lines.
do
printf " %s\n" "${Attrib[index]}"
done
tput sgr0 # Reset terminal.
# See 'tput' docs.
echo
exit 0
# Exercise:
# --------
# Modify this script to pretty-print a poem from a text data file.</pre>
</font>
</td>
</tr>
</tbody>
</table>
</div>
<p>
<a name="ARRAYSYNTAX">
</a>
</p>
<p>배열 변수는 독특한 문법을 가지고 있고, Bash 명령어와 연산자도 배열에 쓸 수 있는
특별한 옵션을 가지고 있습니다.
</p>
<div class="EXAMPLE">
<a name="ARRAYOPS">
</a>
<p>
<b>예제 27-3. 여러가지 배열 연산들</b>
</p>
<table bgcolor="#E0E0E0" border="0" width="100%">
<tbody>
<tr>
<td>
<font color="#000000">
<pre class="PROGRAMLISTING">#!/bin/bash
# array-ops.sh: More fun with arrays.
array=( zero one two three four five )
# Element 0 1 2 3 4 5
echo ${array[0]} # zero
echo ${array:0} # zero
# Parameter expansion of first element,
#+ starting at position # 0 (1st character).
echo ${array:1} # ero
# Parameter expansion of first element,
#+ starting at position # 1 (2nd character).
echo "--------------"
echo ${#array[0]} # 4
# Length of first element of array.
echo ${#array} # 4
# Length of first element of array.
# (Alternate notation)
echo ${#array[1]} # 3
# Length of second element of array.
# Arrays in Bash have zero-based indexing.
echo ${#array[*]} # 6
# Number of elements in array.
echo ${#array[@]} # 6
# Number of elements in array.
echo "--------------"
array2=( [0]="first element" [1]="second element" [3]="fourth element" )
# ^ ^ ^ ^ ^ ^ ^ ^ ^
# Quoting permits embedding whitespace within individual array elements.
echo ${array2[0]} # first element
echo ${array2[1]} # second element
echo ${array2[2]} #
# Skipped in initialization, and therefore null.
echo ${array2[3]} # fourth element
echo ${#array2[0]} # 13 (length of first element)
echo ${#array2[*]} # 3 (number of elements in array)
exit</pre>
</font>
</td>
</tr>
</tbody>
</table>
</div>
<p>
<a name="ARRAYSTRINGOPS">
</a>
</p>
<p>표준
<a href="./string-manipulation.html#STRINGMANIP">문자열 연산</a>
이 배열에서 작동합니다.</p>
<div class="EXAMPLE">
<a name="ARRAYSTROPS">
</a>
<p>
<b>예제 27-4. 배열에서 문자열 연산</b>
</p>
<table bgcolor="#E0E0E0" border="0" width="100%">
<tbody>
<tr>
<td>
<font color="#000000">
<pre class="PROGRAMLISTING">#!/bin/bash
# array-strops.sh: String operations on arrays.
# Script by Michael Zick.
# Used in ABS Guide with permission.
# Fixups: 05 May 08, 04 Aug 08.
# In general, any string operation using the ${name ... } notation
#+ can be applied to all string elements in an array,
#+ with the ${name[@] ... } or ${name[*] ...} notation.
arrayZ=( one two three four five five )
echo
# Trailing Substring Extraction
echo ${arrayZ[@]:0} # one two three four five five
# ^ All elements.
echo ${arrayZ[@]:1} # two three four five five
# ^ All elements following element[0].
echo ${arrayZ[@]:1:2} # two three
# ^ Only the two elements after element[0].
echo "---------"
# Substring Removal
# Removes shortest match from front of string(s).
echo ${arrayZ[@]#f*r} # one two three five five
# ^ # Applied to all elements of the array.
# Matches "four" and removes it.
# Longest match from front of string(s)
echo ${arrayZ[@]##t*e} # one two four five five
# ^^ # Applied to all elements of the array.
# Matches "three" and removes it.
# Shortest match from back of string(s)
echo ${arrayZ[@]%h*e} # one two t four five five
# ^ # Applied to all elements of the array.
# Matches "hree" and removes it.
# Longest match from back of string(s)
echo ${arrayZ[@]%%t*e} # one two four five five
# ^^ # Applied to all elements of the array.
# Matches "three" and removes it.
echo "----------------------"
# Substring Replacement
# Replace first occurrence of substring with replacement.
echo ${arrayZ[@]/fiv/XYZ} # one two three four XYZe XYZe
# ^ # Applied to all elements of the array.
# Replace all occurrences of substring.
echo ${arrayZ[@]//iv/YY} # one two three four fYYe fYYe
# Applied to all elements of the array.
# Delete all occurrences of substring.
# Not specifing a replacement defaults to 'delete' ...
echo ${arrayZ[@]//fi/} # one two three four ve ve
# ^^ # Applied to all elements of the array.
# Replace front-end occurrences of substring.
echo ${arrayZ[@]/#fi/XY} # one two three four XYve XYve
# ^ # Applied to all elements of the array.
# Replace back-end occurrences of substring.
echo ${arrayZ[@]/%ve/ZZ} # one two three four fiZZ fiZZ
# ^ # Applied to all elements of the array.
echo ${arrayZ[@]/%o/XX} # one twXX three four five five
# ^ # Why?
echo "-----------------------------"
replacement() {
echo -n "!!!"
}
echo ${arrayZ[@]/%e/$(replacement)}
# ^ ^^^^^^^^^^^^^^
# on!!! two thre!!! four fiv!!! fiv!!!
# The stdout of replacement() is the replacement string.
# Q.E.D: The replacement action is, in effect, an 'assignment.'
echo "------------------------------------"
# Accessing the "for-each":
echo ${arrayZ[@]//*/$(replacement optional_arguments)}
# ^^ ^^^^^^^^^^^^^
# !!! !!! !!! !!! !!! !!!
# Now, if Bash would only pass the matched string
#+ to the function being called . . .
echo
exit 0
# Before reaching for a Big Hammer -- Perl, Python, or all the rest --
# recall:
# $( ... ) is command substitution.
# A function runs as a sub-process.
# A function writes its output (if echo-ed) to stdout.
# Assignment, in conjunction with "echo" and command substitution,
#+ can read a function's stdout.
# The name[@] notation specifies (the equivalent of) a "for-each"
#+ operation.
# Bash is more powerful than you think!</pre>
</font>
</td>
</tr>
</tbody>
</table>
</div>
<p>
<a href="./commandsub.html#COMMANDSUBREF">명령어 치환</a> 은 배열의 개별적인
요소들을 구성할 수 있습니다.
</p>
<div class="EXAMPLE">
<a name="SCRIPTARRAY">
</a>
<p>
<b>예제 27-5. 스크립트의 내용을 배열로 읽어들이기</b>
</p>
<table bgcolor="#E0E0E0" border="0" width="100%">
<tbody>
<tr>
<td>
<font color="#000000">
<pre class="PROGRAMLISTING">#!/bin/bash
# script-array.sh: Loads this script into an array.
# Inspired by an e-mail from Chris Martin (thanks!).
script_contents=( $(cat "$0") ) # Stores contents of this script ($0)
#+ in an array.
for element in $(seq 0 $((${#script_contents[@]} - 1)))
do # ${#script_contents[@]}
#+ gives number of elements in the array.
#
# Question:
# Why is seq 0 necessary?
# Try changing it to seq 1.
echo -n "${script_contents[$element]}"
# List each field of this script on a single line.
# echo -n "${script_contents[element]}" also works because of ${ ... }.
echo -n " -- " # Use " -- " as a field separator.
done
echo
exit 0
# Exercise:
# --------
# Modify this script so it lists itself
#+ in its original format,
#+ complete with whitespace, line breaks, etc.</pre>
</font>
</td>
</tr>
</tbody>
</table>
</div>
<p>배열 내용에서, 어떤 Bash
<a href="./internal.html#BUILTINREF">내부 명령</a> 은 조금 다른 의미를 갖습니다.
<a name="ARRAYUNSET"></a>예를 들어,
<a href="./internal.html#UNSETREF">unset</a> 은 배열의 요소를 지우거나, 배열 전체를
지웁니다.
</p>
<p>
<a name="ARRAYSPECIALPROPS">
</a>
</p>
<div class="EXAMPLE">
<a name="EX67">
</a>
<p>
<b>예제 27-6. 배열의 특성들</b>
</p>
<table bgcolor="#E0E0E0" border="0" width="100%">
<tbody>
<tr>
<td>
<font color="#000000">
<pre class="PROGRAMLISTING">#!/bin/bash
declare -a colors
# All subsequent commands in this script will treat
#+ the variable "colors" as an array.
echo "Enter your favorite colors (separated from each other by a space)."
read -a colors # Enter at least 3 colors to demonstrate features below.
# Special option to 'read' command,
#+ allowing assignment of elements in an array.
echo
element_count=${#colors[@]}
# Special syntax to extract number of elements in array.
# element_count=${#colors[*]} works also.
#
# The "@" variable allows word splitting within quotes
#+ (extracts variables separated by whitespace).
#
# This corresponds to the behavior of "$@" and "$*"
#+ in positional parameters.
index=0
while [ "$index" -lt "$element_count" ]
do # List all the elements in the array.
echo ${colors[$index]}
# ${colors[index]} also works because it's within ${ ... } brackets.
let "index = $index + 1"
# Or:
# ((index++))
done
# Each array element listed on a separate line.
# If this is not desired, use echo -n "${colors[$index]} "
#
# Doing it with a "for" loop instead:
# for i in "${colors[@]}"
# do
# echo "$i"
# done
# (Thanks, S.C.)
echo
# Again, list all the elements in the array, but using a more elegant method.
echo ${colors[@]} # echo ${colors[*]} also works.
echo
# The "unset" command deletes elements of an array, or entire array.
unset colors[1] # Remove 2nd element of array.
# Same effect as colors[1]=
echo ${colors[@]} # List array again, missing 2nd element.
unset colors # Delete entire array.
# unset colors[*] and
#+ unset colors[@] also work.
echo; echo -n "Colors gone."
echo ${colors[@]} # List array again, now empty.
exit 0</pre>
</font>
</td>
</tr>
</tbody>
</table>
</div>
<p>
<a name="ARRAYNUMELEMENTS">
</a>
</p>
<p>앞의 예에서 볼 수 있듯이,
<b class="COMMAND">${array_name[@]}</b> 나
<b class="COMMAND">${array_name[*]}</b> 는 배열의
<em>모든</em> 요소를 의미합니다. 비슷하게 배열에 있는 요소의 갯수는
<b class="COMMAND">${#array_name[@]}</b> 나
<b class="COMMAND">${#array_name[*]}</b> 를 이용해서 얻을 수 있습니다.
<b class="COMMAND">${#array_name}</b> 는
<b class="COMMAND">${array_name[0]}</b> ,즉 배열의 첫번째 요소의 길이 (문자의 갯수) 입니다.
</p>
<p>
<a name="EMPTYARRAY0">
</a>
</p>
<div class="EXAMPLE">
<a name="EMPTYARRAY">
</a>
<p>
<b>예제 27-7. 빈 배열과 빈 요소</b>
</p>
<table bgcolor="#E0E0E0" border="0" width="100%">
<tbody>
<tr>
<td>
<font color="#000000">
<pre class="PROGRAMLISTING">#!/bin/bash
# empty-array.sh
# Thanks to Stephane Chazelas for the original example,
#+ and to Michael Zick and Omair Eshkenazi, for extending it.
# And to Nathan Coulter for clarifications and corrections.
# An empty array is not the same as an array with empty elements.
array0=( first second third )
array1=( '' ) # "array1" consists of one empty element.
array2=( ) # No elements . . . "array2" is empty.
array3=( ) # What about this array?
echo
ListArray()
{
echo
echo "Elements in array0: ${array0[@]}"
echo "Elements in array1: ${array1[@]}"
echo "Elements in array2: ${array2[@]}"
echo "Elements in array3: ${array3[@]}"
echo
echo "Length of first element in array0 = ${#array0}"
echo "Length of first element in array1 = ${#array1}"
echo "Length of first element in array2 = ${#array2}"
echo "Length of first element in array3 = ${#array3}"
echo
echo "Number of elements in array0 = ${#array0[*]}" # 3
echo "Number of elements in array1 = ${#array1[*]}" # 1 (Surprise!)
echo "Number of elements in array2 = ${#array2[*]}" # 0
echo "Number of elements in array3 = ${#array3[*]}" # 0
}
# ===================================================================
ListArray
# Try extending those arrays.
# Adding an element to an array.
array0=( "${array0[@]}" "new1" )
array1=( "${array1[@]}" "new1" )
array2=( "${array2[@]}" "new1" )
array3=( "${array3[@]}" "new1" )
ListArray
# or
array0[${#array0[*]}]="new2"
array1[${#array1[*]}]="new2"
array2[${#array2[*]}]="new2"
array3[${#array3[*]}]="new2"
ListArray
# When extended as above, arrays are 'stacks' ...
# Above is the 'push' ...
# The stack 'height' is:
height=${#array2[@]}
echo
echo "Stack height for array2 = $height"
# The 'pop' is:
unset array2[${#array2[@]}-1] # Arrays are zero-based,
height=${#array2[@]} #+ which means first element has index 0.
echo
echo "POP"
echo "New stack height for array2 = $height"
ListArray
# List only 2nd and 3rd elements of array0.
from=1 # Zero-based numbering.
to=2
array3=( ${array0[@]:1:2} )
echo
echo "Elements in array3: ${array3[@]}"
# Works like a string (array of characters).
# Try some other "string" forms.
# Replacement:
array4=( ${array0[@]/second/2nd} )
echo
echo "Elements in array4: ${array4[@]}"
# Replace all matching wildcarded string.
array5=( ${array0[@]//new?/old} )
echo
echo "Elements in array5: ${array5[@]}"
# Just when you are getting the feel for this . . .
array6=( ${array0[@]#*new} )
echo # This one might surprise you.
echo "Elements in array6: ${array6[@]}"
array7=( ${array0[@]#new1} )
echo # After array6 this should not be a surprise.
echo "Elements in array7: ${array7[@]}"
# Which looks a lot like . . .
array8=( ${array0[@]/new1/} )
echo
echo "Elements in array8: ${array8[@]}"
# So what can one say about this?
# The string operations are performed on
#+ each of the elements in var[@] in succession.
# Therefore : Bash supports string vector operations.
# If the result is a zero length string,
#+ that element disappears in the resulting assignment.
# However, if the expansion is in quotes, the null elements remain.
# Michael Zick: Question, are those strings hard or soft quotes?
# Nathan Coulter: There is no such thing as "soft quotes."
#! What's really happening is that
#!+ the pattern matching happens after
#!+ all the other expansions of [word]
#!+ in cases like ${parameter#word}.
zap='new*'
array9=( ${array0[@]/$zap/} )
echo
echo "Number of elements in array9: ${#array9[@]}"
array9=( "${array0[@]/$zap/}" )
echo "Elements in array9: ${array9[@]}"
# This time the null elements remain.
echo "Number of elements in array9: ${#array9[@]}"
# Just when you thought you were still in Kansas . . .
array10=( ${array0[@]#$zap} )
echo
echo "Elements in array10: ${array10[@]}"
# But, the asterisk in zap won't be interpreted if quoted.
array10=( ${array0[@]#"$zap"} )
echo
echo "Elements in array10: ${array10[@]}"
# Well, maybe we _are_ still in Kansas . . .
# (Revisions to above code block by Nathan Coulter.)
# Compare array7 with array10.
# Compare array8 with array9.
# Reiterating: No such thing as soft quotes!
# Nathan Coulter explains:
# Pattern matching of 'word' in ${parameter#word} is done after
#+ parameter expansion and *before* quote removal.
# In the normal case, pattern matching is done *after* quote removal.
exit</pre>
</font>
</td>
</tr>
</tbody>
</table>
</div>
<p>
<b class="COMMAND">${array_name[@]}</b> 과
<b class="COMMAND">${array_name[*]}</b> 는
<a href="./internalvariables.html#APPREF">$@ and $*</a> 의 관계와 비슷합니다. 배열의 사용법은
수없이 많습니다.
</p>
<p>
<a name="COPYARRAY0">
</a>
</p>
<p> <table bgcolor="#E0E0E0" border="0" width="100%">
<tbody>
<tr>
<td>
<font color="#000000">
<pre class="PROGRAMLISTING"># Copying an array.
array2=( "${array1[@]}" )
# or
array2="${array1[@]}"
#
# However, this fails with "sparse" arrays,
#+ arrays with holes (missing elements) in them,
#+ as Jochen DeSmet points out.
# ------------------------------------------
array1[0]=0
# array1[1] not assigned
array1[2]=2
array2=( "${array1[@]}" ) # Copy it?
echo ${array2[0]} # 0
echo ${array2[2]} # (null), should be 2
# ------------------------------------------
# Adding an element to an array.
array=( "${array[@]}" "new element" )
# or
array[${#array[*]}]="new element"
# Thanks, S.C.</pre>
</font>
</td>
</tr>
</tbody>
</table>
</p>
<p>
<a name="ARRAYINITCS">
</a>
</p>
<div class="TIP">
<p>
</p>
<table class="TIP" border="0" width="100%">
<tbody>
<tr>
<td align="CENTER" valign="TOP" width="25">
<img src="arrays_files/tip.gif" alt="Tip" hspace="5">
</td>
<td align="LEFT" valign="TOP">
<p>
<a href="./commandsub.html#COMMANDSUBREF">명령어 치환</a> 을 이용해
<b class="COMMAND">array=( element1 element2 ... elementN )</b> 로 배열을 초기화하면, 문서파일의
내용을 배열로 읽어올 수 있습니다.
</p>
<p>
<table bgcolor="#E0E0E0" border="0" width="100%">
<tbody>
<tr>
<td>
<font color="#000000">
<pre class="PROGRAMLISTING">#!/bin/bash
filename=sample_file
# cat sample_file
#
# 1 a b c
# 2 d e fg
declare -a array1
array1=( `cat "$filename"`) # Loads contents
# List file to stdout #+ of $filename into array1.
#
# array1=( `cat "$filename" | tr '\n' ' '`)
# change linefeeds in file to spaces.
# Not necessary because Bash does word splitting,
#+ changing linefeeds to spaces.
echo ${array1[@]} # List the array.
# 1 a b c 2 d e fg
#
# Each whitespace-separated "word" in the file
#+ has been assigned to an element of the array.
element_count=${#array1[*]}
echo $element_count # 8</pre>
</font>
</td>
</tr>
</tbody>
</table>
</p>
</td>
</tr>
</tbody>
</table>
</div>
<p>스크립트를 잘 쓰면 더 많은 배열 연산을 할 수도 있습니다.</p>
<p>
<a name="ARRAYASSIGN0">
</a>
</p>
<div class="EXAMPLE">
<a name="ARRAYASSIGN">
</a>
<p>
<b>예제 27-8. 배열 초기화하기</b>
</p>
<table bgcolor="#E0E0E0" border="0" width="100%">
<tbody>
<tr>
<td>
<font color="#000000">
<pre class="PROGRAMLISTING">#! /bin/bash
# array-assign.bash
# Array operations are Bash-specific,
#+ hence the ".bash" in the script name.
# Copyright (c) Michael S. Zick, 2003, All rights reserved.
# License: Unrestricted reuse in any form, for any purpose.
# Version: $ID$
#
# Clarification and additional comments by William Park.
# Based on an example provided by Stephane Chazelas
#+ which appeared in an earlier version of the
#+ Advanced Bash Scripting Guide.
# Output format of the 'times' command:
# User CPU <space> System CPU
# User CPU of dead children <space> System CPU of dead children
# Bash has two versions of assigning all elements of an array
#+ to a new array variable.
# Both drop 'null reference' elements
#+ in Bash versions 2.04 and later.
# An additional array assignment that maintains the relationship of
#+ [subscript]=value for arrays may be added to newer versions.
# Constructs a large array using an internal command,
#+ but anything creating an array of several thousand elements
#+ will do just fine.
declare -a bigOne=( /dev/* ) # All the files in /dev . . .
echo
echo 'Conditions: Unquoted, default IFS, All-Elements-Of'
echo "Number of elements in array is ${#bigOne[@]}"
# set -vx
echo
echo '- - testing: =( ${array[@]} ) - -'
times
declare -a bigTwo=( ${bigOne[@]} )
# Note parens: ^ ^
times