logo

Bash Array

Šioje temoje parodysime bash masyvo pagrindus ir kaip jie naudojami bash shell scenarijuose.

Masyvas gali būti apibrėžtas kaip panašaus tipo elementų rinkinys. Skirtingai nuo daugelio programavimo kalbų, bash scenarijų masyvai nebūtinai turi būti panašių elementų rinkinys. Kadangi „Bash“ neskiria eilutės nuo skaičiaus, masyve gali būti ir eilučių, ir skaičių.

Bash nepalaiko daugiamačių masyvų; negalime turėti elementų, kurie yra masyvai. „Bash“ palaiko vienmačius skaitiniu būdu indeksuotus masyvus, taip pat asociatyvinius masyvus. Norėdami pasiekti skaitiniu būdu indeksuotą masyvą iš paskutinio, galime naudoti neigiamus indeksus. Indeksas „-1“ bus laikomas paskutinio elemento nuoroda. Masyve galime naudoti kelis elementus.

Bash masyvo deklaracija

Masyvai Bash gali būti deklaruojami šiais būdais:

Skaitmeniškai indeksuotų masyvų kūrimas

Mes galime naudoti bet kurį kintamąjį kaip indeksuotą masyvą jo nedeklaruodami.

Norėdami aiškiai deklaruoti kintamąjį kaip Bash masyvą, naudokite raktinį žodį „declare“ ir sintaksę galima apibrėžti taip:

 declare -a ARRAY_NAME 

kur,

ARRAY_NAME nurodo pavadinimą, kurį priskirtume masyvai.

Pastaba:Kintamojo pavadinimo Bash taisyklės yra tokios pačios, kaip pavadinti masyvą.

Bendras indeksuoto masyvo kūrimo metodas gali būti apibrėžtas tokia forma:

 ARRAY_NAME[index_1]=value_1 ARRAY_NAME[index_2]=value_2 ARRAY_NAME[index_n]=value_n 

kur raktinis žodis „indeksas“ naudojamas teigiamiems sveikiesiems skaičiams apibrėžti.

Asociatyvinių masyvų kūrimas

Skirtingai nuo skaitiniu būdu indeksuotų masyvų, pirmiausia deklaruojami asociatyvūs masyvai. Asociatyviems masyvams deklaruoti galime naudoti raktinį žodį „declare“ ir parinktį -A (didžiosios raidės). Sintaksę galima apibrėžti taip:

 declare -A ARRAY_NAME 

Bendras būdas sukurti asociatyvų masyvą gali būti apibrėžtas tokia forma:

 declare -A ARRAY_NAME ARRAY_NAME[index_foo]=value_foo ARRAY_NAME[index_bar]=value_bar ARRAY_NAME[index_xyz]=value_xyz 

kur indeksas_ naudojamas bet kuriai eilutei apibrėžti.

Aukščiau pateiktą formą taip pat galime parašyti tokiu būdu:

df.loc
 declare -A ARRAY_NAME ARRAY_NAME=( [index_foo]=value_foo [index_bar]=value_bar [index_xyz]=value_xyz ) 

„Bash“ masyvo inicijavimas

Norėdami inicijuoti Bash Array, galime naudoti priskyrimo operatorių (=), nurodydami skliausteliuose esančių elementų sąrašą, atskirtą tarpais, kaip nurodyta toliau:

 ARRAY_NAME=(element_1st element_2nd element_Nth) 

Pastaba:Čia pirmasis elementas turės indeksą 0. Be to, aplink priskyrimo operatorių (=) neturėtų būti vietos.

Pasiekite „Bash Array“ elementus

Norėdami pasiekti Bash masyvo elementus, galime naudoti šią sintaksę:

 echo ${ARRAY_NAME[2]} 

Spausdinti Bash Array

Galime naudoti raktinį žodį „declare“ su „-p“ parinktimi, kad išspausdintume visus „Bash Array“ elementus su visais indeksais ir informacija. „Bash Array“ spausdinimo sintaksė gali būti apibrėžta taip:

 declare -p ARRAY_NAME 

Masyvo operacijos

Kai masyvas yra priskirtas, galime su juo atlikti keletą naudingų operacijų. Galime rodyti jo raktus ir reikšmes, taip pat modifikuoti pridėdami arba pašalindami elementus:

Atskaitos elementai

Norėdami nurodyti vieną elementą, turime žinoti elemento indekso numerį. Galime nurodyti arba spausdinti bet kurį elementą naudodami šią sintaksę:

 ${ARRAY_NAME[index]} 

Pastaba:Garbanotieji skliaustai ${} reikalingi, kad būtų išvengta apvalkalo failo vardo išplėtimo operatorių.

Pavyzdžiui, išspausdinkime masyvo elementą, kurio indeksas yra 2:

Bash scenarijus

 #!/bin/bash #Script to print an element of an array with an index of 2 #declaring the array declare -a example_array=( 'Welcome''To''Javatpoint' ) #printing the element with index of 2 echo ${example_array[2]} 

Išvestis

 Javatpoint 

Jei nurodyto indekso vietoje naudosime @ arba *, jis bus išplėstas iki visų masyvo narių. Norėdami atspausdinti visus elementus, galime naudoti šią formą:

Bash scenarijus

 #!/bin/bash #Script to print all the elements of the array #declaring the array declare -a example_array=( 'Welcome''To''Javatpoint' ) #Printing all the elements echo '${example_array[@]}' 

Išvestis

 Welcome to Javatpoint 

Vienintelis skirtumas tarp @ ir * yra tas, kad naudojant @ forma yra apsupta dvigubomis kabutėmis. Pirmuoju atveju (naudojant @) išplėtimas pateikia kiekvieno masyvo elemento žodį. Jį galima geriau apibūdinti naudojant „ciklą“. Tarkime, kad turime masyvą su trimis elementais: „Sveiki atvykę“, „Kam“ ir „Javatpoint“:

 $ example_array= (Welcome to Javatpoint) 

Taikant kilpą su @:

 for i in '${example_array[@]}'; do echo '$i'; done 

Tai duos tokį rezultatą:

grąžinimo tipas java
 Welcome To Javatpoint 

Pritaikius kilpą su *, bus gautas vienas rezultatas, laikantis visus masyvo elementus kaip vieną žodį:

 Welcome To Javatpoint 

Svarbu suprasti @ ir * naudojimą, nes tai naudinga naudojant formą norint kartoti masyvo elementus.

Masyvo raktų spausdinimas

Taip pat galime nuskaityti ir atspausdinti raktus, naudojamus indeksuotuose arba asociatyviniuose masyvuose, o ne atitinkamas jų vertes. Tai galima atlikti pridedant ! operatorius prieš masyvo pavadinimą, kaip nurodyta toliau:

koks mano monitoriaus dydis
 ${!ARRAY_NAME[index]} 

Pavyzdys

 #!/bin/bash #Script to print the keys of the array #Declaring the Array declare -a example_array=( 'Welcome''To''Javatpoint' ) #Printing the Keys echo '${!example_array[@]}' 

Išvestis

 0 1 2 

Masyvo ilgio radimas

Elementų, esančių masyve, skaičių galime suskaičiuoti naudodami šią formą:

 ${#ARRAY_NAME[@]} 

Pavyzdys

 #!/bin/bash #Declaring the Array declare -a example_array=( 'Welcome''To''Javatpoint' ) #Printing Array Length echo 'The array contains ${#example_array[@]} elements' 

Išvestis

 The array contains 3 elements 

Pereikite per masyvą

Bendras būdas kartoti kiekvieną masyvo elementą yra naudoti „ciklą“.

Pavyzdys

 #!/bin/bash #Script to print all keys and values using loop through the array declare -a example_array=( 'Welcome''To''Javatpoint' ) #Array Loop for i in '${!example_array[@]}' do echo The key value of element '${example_array[$i]}' is '$i' done 

Išvestis

Bash Array

Kitas įprastas masyvo kilpos būdas yra gauti masyvo ilgį ir naudoti C stiliaus kilpą:

Bash scenarijus

 #!/bin/bash #Script to loop through an array in C-style declare -a example_array=( &apos;Welcome&apos;&apos;To&apos;&apos;Javatpoint&apos; ) #Length of the Array length=${#example_array[@]} #Array Loop for (( i=0; i <${length}; i++ )) do echo $i ${example_array[$i]} done < pre> <p> <strong>Output</strong> </p> <img src="//techcodeview.com/img/bash-tutorial/77/bash-array-2.webp" alt="Bash Array"> <h3>Adding Elements to an Array</h3> <p>We have an option to add elements to an indexed or associative array by specifying their index or associative key respectively. To add the new element to an array in bash, we can use the following form:</p> <pre> ARRAY_NAME[index_n]=&apos;New Element&apos; </pre> <p> <strong>Example</strong> </p> <pre> #!/bin/bash #Declaring an array declare -a example_array=( &apos;Java&apos;&apos;Python&apos;&apos;PHP&apos;&apos;HTML&apos; ) #Adding new element example_array[4]=&apos;JavaScript&apos; #Printing all the elements echo &apos;${example_array[@]}&apos; </pre> <p> <strong>Output</strong> </p> <pre> Java Python PHP HTML JavaScript </pre> <p>Another method for adding a new element to an array is by using the += operator. There is no need to specify the index in this method. We can add one or multiple elements in the array by using the following way:</p> <p> <strong>Example</strong> </p> <pre> #!/bin/bash #Declaring the Array declare -a example_array=( &apos;Java&apos;&apos;Python&apos;&apos;PHP&apos; ) #Adding new elements example_array+=( JavaScript CSS SQL ) #Printing all the elements echo &apos;${example_array[@]}&apos; </pre> <p> <strong>Output</strong> </p> <pre> Java Python PHP JavaScript CSS SQL </pre> <h3>Updating Array Element</h3> <p>We can update the array element by assigning a new value to the existing array by its index value. Let&apos;s change the array element at index 4 with an element &apos;Javatpoint&apos;.</p> <p> <strong>Example</strong> </p> <pre> #!/bin/bash #Script to update array element #Declaring the array declare -a example_array=( &apos;We&apos;&apos;welcome&apos;&apos;you&apos;&apos;on&apos;&apos;SSSIT&apos; ) #Updating the Array Element example_array[4]=Javatpoint #Printig all the elements of the Array echo ${example_array[@]} </pre> <p> <strong>Output</strong> </p> <pre> We welcome you on Javatpoint </pre> <h3>Deleting an Element from an Array</h3> <p>If we want to delete the element from the array, we have to know its index or key in case of an associative array. An element can be removed by using the &apos; <strong>unset</strong> &apos; command:</p> <pre> unset ARRAY_NAME[index] </pre> <p>An example is shown below to provide you a better understanding of this concept:</p> <p> <strong>Example</strong> </p> <pre> #!/bin/bash #Script to delete the element from the array #Declaring the array declare -a example_array=( &apos;Java&apos;&apos;Python&apos;&apos;HTML&apos;&apos;CSS&apos;&apos;JavaScript&apos; ) #Removing the element unset example_array[1] #Printing all the elements after deletion echo &apos;${example_array[@]}&apos; </pre> <p> <strong>Output</strong> </p> <pre> Java HTML CSS JavaScript </pre> <p>Here, we have created a simple array consisting of five elements, &apos;Java&apos;, &apos;Python&apos;, &apos;HTML&apos;, &apos;CSS&apos; and &apos;JavaScript&apos;. Then we removed the element &apos;Python&apos; from the array by using &apos;unset&apos; and referencing the index of it. The index of element &apos;Python&apos; was &apos;1&apos;, since bash arrays start from 0. If we check the indexes of the array after removing the element, we can see that the index for the removed element is missing. We can check the indexes by adding the following command into the script:</p> <pre> echo ${!example_array[@]} </pre> <p>The output will look like:</p> <pre> 0 2 3 4 </pre> <p>This concept also works for the associative arrays.</p> <h3>Deleting the Entire Array</h3> <p>Deleting an entire array is a very simple task. It can be performed by passing the array name as an argument to the &apos; <strong>unset</strong> &apos; command without specifying the index or key.</p> <p> <strong>Example</strong> </p> <pre> #!/bin/bash #Script to delete the entire Array #Declaring the Array declare -a example_array=( &apos;Java&apos;&apos;Python&apos;&apos;HTML&apos;&apos;CSS&apos;&apos;JavaScript&apos; ) #Deleting Entire Array unset example_array #Printing the Array Elements echo ${!example_array[@]} #Printing the keys echo ${!example_array[@]} </pre> <p> <strong>Output</strong> </p> <img src="//techcodeview.com/img/bash-tutorial/77/bash-array-3.webp" alt="Bash Array"> <p>There will be no output if we try to print the content of the above script. An empty result is returned because the array doesn&apos;t exist anymore.</p> <h3>Slice Array Elements</h3> <p>Bash arrays can also be sliced from a given starting index to the ending index.</p> <p>To slice an array from starting index &apos;m&apos; to an ending index &apos;n&apos;, we can use the following syntax:</p> <pre> SLICED_ARRAY=(${ARRAY_NAME[@]:m:n}&apos;) </pre> <p> <strong>Example</strong> </p> <pre> #!/bin/bash #Script to slice Array Element from index 1 to index 3 #Declaring the Array example_array=( &apos;Java&apos;&apos;Python&apos;&apos;HTML&apos;&apos;CSS&apos;&apos;JavaScript&apos; ) #Slicing the Array sliced_array=(&apos;${example_array[@]:1:3}&apos;) #Applying for loop to iterate over each element in Array for i in &apos;${sliced_array[@]}&apos; do echo $i done </pre> <p> <strong>Output</strong> </p> <img src="//techcodeview.com/img/bash-tutorial/77/bash-array-4.webp" alt="Bash Array"> <hr></${length};>

Pavyzdys

 #!/bin/bash #Declaring an array declare -a example_array=( &apos;Java&apos;&apos;Python&apos;&apos;PHP&apos;&apos;HTML&apos; ) #Adding new element example_array[4]=&apos;JavaScript&apos; #Printing all the elements echo &apos;${example_array[@]}&apos; 

Išvestis

 Java Python PHP HTML JavaScript 

Kitas būdas įtraukti naują elementą į masyvą yra naudoti += operatorių. Taikant šį metodą indekso nurodyti nereikia. Į masyvą galime įtraukti vieną ar kelis elementus tokiu būdu:

Pavyzdys

 #!/bin/bash #Declaring the Array declare -a example_array=( &apos;Java&apos;&apos;Python&apos;&apos;PHP&apos; ) #Adding new elements example_array+=( JavaScript CSS SQL ) #Printing all the elements echo &apos;${example_array[@]}&apos; 

Išvestis

 Java Python PHP JavaScript CSS SQL 

Atnaujinamas masyvo elementas

Masyvo elementą galime atnaujinti priskirdami naują reikšmę esamam masyvui pagal jo indekso reikšmę. Pakeiskime 4 indekso masyvo elementą elementu „Javatpoint“.

Pavyzdys

 #!/bin/bash #Script to update array element #Declaring the array declare -a example_array=( &apos;We&apos;&apos;welcome&apos;&apos;you&apos;&apos;on&apos;&apos;SSSIT&apos; ) #Updating the Array Element example_array[4]=Javatpoint #Printig all the elements of the Array echo ${example_array[@]} 

Išvestis

 We welcome you on Javatpoint 

Elemento ištrynimas iš masyvo

Jei norime ištrinti elementą iš masyvo, turime žinoti jo indeksą arba raktą asociatyvaus masyvo atveju. Elementą galima pašalinti naudojant „ nenustatyta ' komanda:

registro perdavimo logika
 unset ARRAY_NAME[index] 

Toliau pateikiamas pavyzdys, kad geriau suprastumėte šią sąvoką:

Pavyzdys

 #!/bin/bash #Script to delete the element from the array #Declaring the array declare -a example_array=( &apos;Java&apos;&apos;Python&apos;&apos;HTML&apos;&apos;CSS&apos;&apos;JavaScript&apos; ) #Removing the element unset example_array[1] #Printing all the elements after deletion echo &apos;${example_array[@]}&apos; 

Išvestis

 Java HTML CSS JavaScript 

Čia sukūrėme paprastą masyvą, kurį sudaro penki elementai: „Java“, „Python“, „HTML“, „CSS“ ir „JavaScript“. Tada mes pašalinome elementą „Python“ iš masyvo naudodami „unset“ ir nurodydami jo indeksą. Elemento 'Python' indeksas buvo '1', nes bash masyvai prasideda nuo 0. Jei pašalinus elementą patikrintume masyvo indeksus, pamatytume, kad trūksta pašalinto elemento indekso. Indeksus galime patikrinti pridėdami šią komandą į scenarijų:

 echo ${!example_array[@]} 

Išvestis atrodys taip:

 0 2 3 4 

Ši koncepcija taip pat tinka asociatyviems masyvams.

Viso masyvo ištrynimas

Viso masyvo ištrynimas yra labai paprasta užduotis. Tai galima atlikti perduodant masyvo pavadinimą kaip argumentą į ' nenustatyta ' komandą nenurodydami indekso ar rakto.

Pavyzdys

 #!/bin/bash #Script to delete the entire Array #Declaring the Array declare -a example_array=( &apos;Java&apos;&apos;Python&apos;&apos;HTML&apos;&apos;CSS&apos;&apos;JavaScript&apos; ) #Deleting Entire Array unset example_array #Printing the Array Elements echo ${!example_array[@]} #Printing the keys echo ${!example_array[@]} 

Išvestis

Bash Array

Nebus jokios išvesties, jei bandysime atspausdinti aukščiau pateikto scenarijaus turinį. Grąžinamas tuščias rezultatas, nes masyvo nebėra.

Supjaustykite masyvo elementus

Bash masyvai taip pat gali būti suskirstyti nuo nurodyto pradžios indekso iki pabaigos indekso.

Norėdami padalyti masyvą nuo pradžios indekso „m“ iki pabaigos indekso „n“, galime naudoti šią sintaksę:

 SLICED_ARRAY=(${ARRAY_NAME[@]:m:n}&apos;) 

Pavyzdys

 #!/bin/bash #Script to slice Array Element from index 1 to index 3 #Declaring the Array example_array=( &apos;Java&apos;&apos;Python&apos;&apos;HTML&apos;&apos;CSS&apos;&apos;JavaScript&apos; ) #Slicing the Array sliced_array=(&apos;${example_array[@]:1:3}&apos;) #Applying for loop to iterate over each element in Array for i in &apos;${sliced_array[@]}&apos; do echo $i done 

Išvestis

Bash Array