SlideShare a Scribd company logo
Arrays in Linux


An array is a variable containing multiple values may be of same type or of


different type. There is no maximum limit to the size of an array, nor any


requirement that member variables be indexed or assigned contiguously. Array


index starts with zero.




1. Declaring an Array and Assigning values



In bash, array is created automatically when a variable is used in the format like,


name[index]=value




      name is any name for an array


      index could be any number or expression that must evaluate to a number


    greater than or equal to zero.You can declare an explicit array using declare -a


    arrayname.
$ cat arraymanip.sh


#! /bin/bash


Unix[0]='Debian'


Unix[1]='Red hat'


Unix[2]='Ubuntu'


Unix[3]='Suse'




echo ${Unix[1]}




$./arraymanip.sh


Red hat




To access an element from an array use curly brackets like ${name[index]}.




2. Initializing an array during declaration
Instead of initializing an each element of an array separately, you can declare and


initialize an array by specifying the list of elements (separated by white space) with


in a curly braces.


Syntax:


declare -a arrayname=(element1 element2 element3)




If the elements has the white space character, enclose it with in a quotes.


#! /bin/bash


$cat arraymanip.sh


declare -a Unix=('Debian' 'Red hat' 'Red hat' 'Suse' 'Fedora');




declare -a declares an array and all the elements in the parentheses are the


elements of an array.




3. Print the Whole Bash Array
There are different ways to print the whole elements of the array. If the index


number is @ or *, all members of an array are referenced. You can traverse


through the array elements and print it, using looping statements in bash.


echo ${Unix[@]}




# Add the above echo statement into the arraymanip.sh


#./t.sh


Debian Red hat Ubuntu Suse




Referring to the content of a member variable of an array without providing an


index number is the same as referring to the content of the first element, the one


referenced with index number zero.




4. Length of the Bash Array



We can get the length of an array using the special parameter called $#.
${#arrayname[@]} gives you the length of the array.


$ cat arraymanip.sh


declare -a Unix=('Debian' 'Red hat' 'Suse' 'Fedora');


echo ${#Unix[@]} #Number of elements in the array


echo ${#Unix} #Number of characters in the first element of the
array.i.e Debian


$./arraymanip.sh


4


6




5. Length of the nth Element in an Array



${#arrayname[n]} should give the length of the nth element in an array.


$cat arraymanip.sh


#! /bin/bash




Unix[0]='Debian'
Unix[1]='Red hat'


Unix[2]='Ubuntu'


Unix[3]='Suse'




echo ${#Unix[3]} # length of the element located at index 3 i.e
Suse




$./arraymanip.sh


4




6. Extraction by offset and length for an array



The following example shows the way to extract 2 elements starting from the


position 3 from an array called Unix.


$cat arraymanip.sh


Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS'
'OpenLinux');


echo ${Unix[@]:3:2}
$./arraymanip.sh


Suse Fedora




The above example returns the elements in the 3rd index and fourth index. Index


always starts with zero.




7. Extraction with offset and length, for a particular element of an array



To extract only first four elements from an array element . For example, Ubuntu


which is located at the second index of an array, you can use offset and length for


a particular element of an array.


$cat arraymanip.sh


#! /bin/bash




Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS'
'OpenLinux');
echo ${Unix[2]:0:4}




./arraymanip.sh


Ubun




The above example extracts the first four characters from the 2nd indexed element


of an array.




8. Search and Replace in an array elements



The following example, searches for Ubuntu in an array elements, and replace the


same with the word ‘SCO Unix’.


$cat arraymanip.sh


#!/bin/bash


Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS'
'OpenLinux');
echo ${Unix[@]/Ubuntu/SCO Unix}




$./arraymanip.sh


Debian Red hat SCO Unix Suse Fedora UTS OpenLinux




In this example, it replaces the element in the 2nd index ‘Ubuntu’ with ‘SCO Unix’.


But this example will not permanently replace the array content.




9. Add an element to an existing Bash Array



The following example shows the way to add an element to the existing array.


$cat arraymanip.sh


Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS'
'OpenLinux');


Unix=("${Unix[@]}" "AIX" "HP-UX")


echo ${Unix[7]}
$./arraymanip.sh


AIX




In the array called Unix, the elements ‘AIX’ and ‘HP-UX’ are added in 7th and 8th


index respectively.




10. Remove an Element from an Array



unset is used to remove an element from an array.unset will have the same effect


as assigning null to an element.


$cat arraymanip.sh


#!/bin/bash


Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS'
'OpenLinux');




unset Unix[3]


echo ${Unix[3]}
The above script will just print null which is the value available in the 3rd index. The


following example shows one of the way to remove an element completely from an


array.


$ cat arraymanip.sh


Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS'
'OpenLinux');


pos=3


Unix=(${Unix[@]:0:$pos} ${Unix[@]:$(($pos + 1))})


echo ${Unix[@]}




$./arraymanip.sh


Debian Red hat Ubuntu Fedora UTS OpenLinux




In this example, ${Unix[@]:0:$pos} will give you 3 elements starting from 0th index


i.e 0,1,2 and ${Unix[@]:4} will give the elements from 4th index to the last index.
And merge both the above output. This is one of the workaround to remove an


element from an array.




11. Remove Bash Array Elements using Patterns



In the search condition you can give the patterns, and stores the remaining


element to an another array as shown below.


$ cat arraymanip.sh


#!/bin/bash


declare -a Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora');


declare -a patter=( ${Unix[@]/Red*/} )


echo ${patter[@]}




$ ./arraymanip.sh


Debian Ubuntu Suse Fedora
The above example removes the elements which has the patter Red*.




12. Copying an Array



Expand the array elements and store that into a new array as shown below.


#!/bin/bash


Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS'
'OpenLinux');


Linux=("${Unix[@]}")


echo ${Linux[@]}




$ ./arraymanip.sh


Debian Red hat Ubuntu Fedora UTS OpenLinux




13. Concatenation of two Bash Arrays



Expand the elements of the two arrays and assign it to the new array.


$cat arraymanip.sh
#!/bin/bash


Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS'
'OpenLinux');


Shell=('bash' 'csh' 'jsh' 'rsh' 'ksh' 'rc' 'tcsh');




UnixShell=("${Unix[@]}" "${Shell[@]}")


echo ${UnixShell[@]}


echo ${#UnixShell[@]}




$ ./arraymanip.sh


Debian Red hat Ubuntu Suse Fedora UTS OpenLinux bash csh jsh rsh
ksh rc tcsh


14




It prints the array which has the elements of the both the array ‘Unix’ and ‘Shell’,


and number of elements of the new array is 14.
14. Deleting an Entire Array



unset is used to delete an entire array.


$cat arraymanip.sh


#!/bin/bash


Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS'
'OpenLinux');


Shell=('bash' 'csh' 'jsh' 'rsh' 'ksh' 'rc' 'tcsh');




UnixShell=("${Unix[@]}" "${Shell[@]}")


unset UnixShell


echo ${#UnixShell[@]}




$ ./arraymanip.sh


0




After unset an array, its length would be zero as shown above.
15. Load Content of a File into an Array



You can load the content of the file line by line into an array.


#Example file


$ cat logfile


Welcome


to


thegeekstuff


Linux


Unix




$ cat loadcontent.sh


#!/bin/bash


filecontent=( `cat "logfile" `)




for t in "${filecontent[@]}"
do


echo $t


done


echo "Read file content!"




$ ./loadcontent.sh


Welcome


to


thegeekstuff


Linux


Unix


Read file content!




In the above example, each index of an array element has printed through for loop.

More Related Content

What's hot

Virtual Private Network(VPN)
Virtual Private Network(VPN)Virtual Private Network(VPN)
Virtual Private Network(VPN)
Abrish06
 
Wireshark Basic Presentation
Wireshark Basic PresentationWireshark Basic Presentation
Wireshark Basic Presentation
MD. SHORIFUL ISLAM
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures tree
maamir farooq
 
Tcp Udp Icmp And The Transport Layer
Tcp Udp Icmp And The Transport LayerTcp Udp Icmp And The Transport Layer
Tcp Udp Icmp And The Transport Layer
tmavroidis
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applications
somendra kumar
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
Rajkiran Nadar
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
shameen khan
 
Client server model
Client server modelClient server model
Client server model
Gd Goenka University
 
Slides of SNMP (Simple network management protocol)
Slides of SNMP (Simple network management protocol)Slides of SNMP (Simple network management protocol)
Slides of SNMP (Simple network management protocol)
Shahrukh Ali Khan
 
Mac addresses(media access control)
Mac addresses(media access control)Mac addresses(media access control)
Mac addresses(media access control)
Ismail Mukiibi
 
Transaction Properties in database | ACID Properties
Transaction Properties in database | ACID PropertiesTransaction Properties in database | ACID Properties
Transaction Properties in database | ACID Properties
nomanbarki
 
Trees in data structures
Trees in data structuresTrees in data structures
Trees in data structures
ASairamSairam1
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
Apurbo Datta
 
DATABASE MANAGEMENT SYSTEM LAB.pdf
DATABASE MANAGEMENT SYSTEM LAB.pdfDATABASE MANAGEMENT SYSTEM LAB.pdf
DATABASE MANAGEMENT SYSTEM LAB.pdf
Prof. Dr. K. Adisesha
 
Wireshark
WiresharkWireshark
Wireshark
ashiesh0007
 
Ipv4 and Ipv6
Ipv4 and Ipv6Ipv4 and Ipv6
Ipv4 and Ipv6
Rishav Bhurtel
 
Ppt on Linked list,stack,queue
Ppt on Linked list,stack,queuePpt on Linked list,stack,queue
Ppt on Linked list,stack,queue
Srajan Shukla
 
Wireshark
WiresharkWireshark
Wireshark
Sourav Roy
 
Cn ipv4 addressing
Cn ipv4 addressingCn ipv4 addressing
Cn ipv4 addressing
SangeethaSasi1
 
Stack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi LecturerStack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi Lecturer
gomathi chlm
 

What's hot (20)

Virtual Private Network(VPN)
Virtual Private Network(VPN)Virtual Private Network(VPN)
Virtual Private Network(VPN)
 
Wireshark Basic Presentation
Wireshark Basic PresentationWireshark Basic Presentation
Wireshark Basic Presentation
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures tree
 
Tcp Udp Icmp And The Transport Layer
Tcp Udp Icmp And The Transport LayerTcp Udp Icmp And The Transport Layer
Tcp Udp Icmp And The Transport Layer
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applications
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
Client server model
Client server modelClient server model
Client server model
 
Slides of SNMP (Simple network management protocol)
Slides of SNMP (Simple network management protocol)Slides of SNMP (Simple network management protocol)
Slides of SNMP (Simple network management protocol)
 
Mac addresses(media access control)
Mac addresses(media access control)Mac addresses(media access control)
Mac addresses(media access control)
 
Transaction Properties in database | ACID Properties
Transaction Properties in database | ACID PropertiesTransaction Properties in database | ACID Properties
Transaction Properties in database | ACID Properties
 
Trees in data structures
Trees in data structuresTrees in data structures
Trees in data structures
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
DATABASE MANAGEMENT SYSTEM LAB.pdf
DATABASE MANAGEMENT SYSTEM LAB.pdfDATABASE MANAGEMENT SYSTEM LAB.pdf
DATABASE MANAGEMENT SYSTEM LAB.pdf
 
Wireshark
WiresharkWireshark
Wireshark
 
Ipv4 and Ipv6
Ipv4 and Ipv6Ipv4 and Ipv6
Ipv4 and Ipv6
 
Ppt on Linked list,stack,queue
Ppt on Linked list,stack,queuePpt on Linked list,stack,queue
Ppt on Linked list,stack,queue
 
Wireshark
WiresharkWireshark
Wireshark
 
Cn ipv4 addressing
Cn ipv4 addressingCn ipv4 addressing
Cn ipv4 addressing
 
Stack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi LecturerStack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi Lecturer
 

Viewers also liked

Top 8 non profit administrative assistant resume samples
Top 8 non profit administrative assistant resume samplesTop 8 non profit administrative assistant resume samples
Top 8 non profit administrative assistant resume samples
tonychoper4305
 
Vision of NSTU-Science Club: Galactic Cluster
Vision of NSTU-Science Club: Galactic ClusterVision of NSTU-Science Club: Galactic Cluster
Vision of NSTU-Science Club: Galactic Cluster
Tahsin Abrar
 
Sdfgdfgdfg
SdfgdfgdfgSdfgdfgdfg
Sdfgdfgdfgtasyrif
 
Top 8 relocation coordinator resume samples
Top 8 relocation coordinator resume samplesTop 8 relocation coordinator resume samples
Top 8 relocation coordinator resume samples
stewardmurler
 
No matter your age
No matter your ageNo matter your age
No matter your age
Shavawn Kurzweil
 
IVR-Games
IVR-GamesIVR-Games
IVR-Games
Sergey Kochugov
 
Laalaala
LaalaalaLaalaala
Laalaala
yermomlovesyou
 
Dethi hsgqg-tieng anh-2011
Dethi hsgqg-tieng anh-2011Dethi hsgqg-tieng anh-2011
Dethi hsgqg-tieng anh-2011
Hườngg Thu
 
Funktionmerkki, ensimmäisen asteen funktio
Funktionmerkki, ensimmäisen asteen funktioFunktionmerkki, ensimmäisen asteen funktio
Funktionmerkki, ensimmäisen asteen funktioteemunmatikka
 
The Pyramid Match Kernel: Discriminative Classification with Sets of Image Fe...
The Pyramid Match Kernel: Discriminative Classification with Sets of Image Fe...The Pyramid Match Kernel: Discriminative Classification with Sets of Image Fe...
The Pyramid Match Kernel: Discriminative Classification with Sets of Image Fe...
wolf
 
Speciale violenza sulle donne
Speciale violenza sulle donneSpeciale violenza sulle donne
Speciale violenza sulle donne
th-teva
 
Hikayat langlang buana
Hikayat langlang buanaHikayat langlang buana
Hikayat langlang buana
wawanasuhanajib
 
الخوف من سوء الخاتمة
 الخوف من سوء الخاتمة الخوف من سوء الخاتمة
الخوف من سوء الخاتمة
ابراهيم حسن
 
Work order management guide
Work order management guideWork order management guide
Work order management guide
zhouxg
 
Tai lieu luyen thi dai hoc mon anh grammar practice
Tai lieu luyen thi dai hoc mon anh   grammar practiceTai lieu luyen thi dai hoc mon anh   grammar practice
Tai lieu luyen thi dai hoc mon anh grammar practice
Trungtâmluyệnthi Qsc
 
L'Oréal, World Leader In Beauty: Makeup, Cosmetics, Haircare and Perfume. An ...
L'Oréal, World Leader In Beauty: Makeup, Cosmetics, Haircare and Perfume. An ...L'Oréal, World Leader In Beauty: Makeup, Cosmetics, Haircare and Perfume. An ...
L'Oréal, World Leader In Beauty: Makeup, Cosmetics, Haircare and Perfume. An ...
Tomno Enock
 
Sample IELTS Writing Task 2
Sample IELTS Writing Task 2Sample IELTS Writing Task 2
Sample IELTS Writing Task 2
Sun Ou
 
Teknik audit
Teknik auditTeknik audit
Teknik audit
Wage Chaniago
 
Police recruitment interview questions
Police recruitment interview questionsPolice recruitment interview questions
Police recruitment interview questions
selinasimpson89
 

Viewers also liked (20)

Top 8 non profit administrative assistant resume samples
Top 8 non profit administrative assistant resume samplesTop 8 non profit administrative assistant resume samples
Top 8 non profit administrative assistant resume samples
 
Vision of NSTU-Science Club: Galactic Cluster
Vision of NSTU-Science Club: Galactic ClusterVision of NSTU-Science Club: Galactic Cluster
Vision of NSTU-Science Club: Galactic Cluster
 
Sdfgdfgdfg
SdfgdfgdfgSdfgdfgdfg
Sdfgdfgdfg
 
Top 8 relocation coordinator resume samples
Top 8 relocation coordinator resume samplesTop 8 relocation coordinator resume samples
Top 8 relocation coordinator resume samples
 
No matter your age
No matter your ageNo matter your age
No matter your age
 
IVR-Games
IVR-GamesIVR-Games
IVR-Games
 
Fotosintesis
FotosintesisFotosintesis
Fotosintesis
 
Laalaala
LaalaalaLaalaala
Laalaala
 
Dethi hsgqg-tieng anh-2011
Dethi hsgqg-tieng anh-2011Dethi hsgqg-tieng anh-2011
Dethi hsgqg-tieng anh-2011
 
Funktionmerkki, ensimmäisen asteen funktio
Funktionmerkki, ensimmäisen asteen funktioFunktionmerkki, ensimmäisen asteen funktio
Funktionmerkki, ensimmäisen asteen funktio
 
The Pyramid Match Kernel: Discriminative Classification with Sets of Image Fe...
The Pyramid Match Kernel: Discriminative Classification with Sets of Image Fe...The Pyramid Match Kernel: Discriminative Classification with Sets of Image Fe...
The Pyramid Match Kernel: Discriminative Classification with Sets of Image Fe...
 
Speciale violenza sulle donne
Speciale violenza sulle donneSpeciale violenza sulle donne
Speciale violenza sulle donne
 
Hikayat langlang buana
Hikayat langlang buanaHikayat langlang buana
Hikayat langlang buana
 
الخوف من سوء الخاتمة
 الخوف من سوء الخاتمة الخوف من سوء الخاتمة
الخوف من سوء الخاتمة
 
Work order management guide
Work order management guideWork order management guide
Work order management guide
 
Tai lieu luyen thi dai hoc mon anh grammar practice
Tai lieu luyen thi dai hoc mon anh   grammar practiceTai lieu luyen thi dai hoc mon anh   grammar practice
Tai lieu luyen thi dai hoc mon anh grammar practice
 
L'Oréal, World Leader In Beauty: Makeup, Cosmetics, Haircare and Perfume. An ...
L'Oréal, World Leader In Beauty: Makeup, Cosmetics, Haircare and Perfume. An ...L'Oréal, World Leader In Beauty: Makeup, Cosmetics, Haircare and Perfume. An ...
L'Oréal, World Leader In Beauty: Makeup, Cosmetics, Haircare and Perfume. An ...
 
Sample IELTS Writing Task 2
Sample IELTS Writing Task 2Sample IELTS Writing Task 2
Sample IELTS Writing Task 2
 
Teknik audit
Teknik auditTeknik audit
Teknik audit
 
Police recruitment interview questions
Police recruitment interview questionsPolice recruitment interview questions
Police recruitment interview questions
 

Similar to Arrays in linux

Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvvLecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
ZahouAmel1
 
Array properties
Array propertiesArray properties
Array properties
Shravan Sharma
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
Mohammed Khan
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
info309708
 
Recursion Lecture in C++
Recursion Lecture in C++Recursion Lecture in C++
Recursion Lecture in C++
Raffi Khatchadourian
 
Unit 2-Arrays.pptx
Unit 2-Arrays.pptxUnit 2-Arrays.pptx
Unit 2-Arrays.pptx
mythili213835
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
Frayosh Wadia
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
Frayosh Wadia
 
Collections framework
Collections frameworkCollections framework
Collections framework
Anand Buddarapu
 
Advanced perl finer points ,pack&unpack,eval,files
Advanced perl   finer points ,pack&unpack,eval,filesAdvanced perl   finer points ,pack&unpack,eval,files
Advanced perl finer points ,pack&unpack,eval,files
Shankar D
 
Unit 1-array,lists and hashes
Unit 1-array,lists and hashesUnit 1-array,lists and hashes
Unit 1-array,lists and hashes
sana mateen
 
Chapter 2 wbp.pptx
Chapter 2 wbp.pptxChapter 2 wbp.pptx
Chapter 2 wbp.pptx
40NehaPagariya
 
Array lecture
Array lectureArray lecture
Array lecture
Joan Saño
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
you will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdfyou will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdf
clearvisioneyecareno
 
Recursion Lecture in Java
Recursion Lecture in JavaRecursion Lecture in Java
Recursion Lecture in Java
Raffi Khatchadourian
 
15 ruby arrays
15 ruby arrays15 ruby arrays
15 ruby arrays
Walker Maidana
 
Java arrays (1)
Java arrays (1)Java arrays (1)
Java arrays (1)
Liza Abello
 
Module7
Module7Module7
Module7
Seid Hussein
 
Array Data Structure & it's type........
Array Data Structure & it's type........Array Data Structure & it's type........
Array Data Structure & it's type........
Jadavapur University
 

Similar to Arrays in linux (20)

Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvvLecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
Lecture 5 array in PHP.pptxLecture 10 CSS part 2.pptxvvvvvvvvvvvvvv
 
Array properties
Array propertiesArray properties
Array properties
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
 
Recursion Lecture in C++
Recursion Lecture in C++Recursion Lecture in C++
Recursion Lecture in C++
 
Unit 2-Arrays.pptx
Unit 2-Arrays.pptxUnit 2-Arrays.pptx
Unit 2-Arrays.pptx
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
Collections framework
Collections frameworkCollections framework
Collections framework
 
Advanced perl finer points ,pack&unpack,eval,files
Advanced perl   finer points ,pack&unpack,eval,filesAdvanced perl   finer points ,pack&unpack,eval,files
Advanced perl finer points ,pack&unpack,eval,files
 
Unit 1-array,lists and hashes
Unit 1-array,lists and hashesUnit 1-array,lists and hashes
Unit 1-array,lists and hashes
 
Chapter 2 wbp.pptx
Chapter 2 wbp.pptxChapter 2 wbp.pptx
Chapter 2 wbp.pptx
 
Array lecture
Array lectureArray lecture
Array lecture
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
you will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdfyou will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdf
 
Recursion Lecture in Java
Recursion Lecture in JavaRecursion Lecture in Java
Recursion Lecture in Java
 
15 ruby arrays
15 ruby arrays15 ruby arrays
15 ruby arrays
 
Java arrays (1)
Java arrays (1)Java arrays (1)
Java arrays (1)
 
Module7
Module7Module7
Module7
 
Array Data Structure & it's type........
Array Data Structure & it's type........Array Data Structure & it's type........
Array Data Structure & it's type........
 

More from Whaleejaa Wha

Windows 7
Windows 7Windows 7
Windows 7
Whaleejaa Wha
 
Windows 7 avanzado
Windows 7 avanzadoWindows 7 avanzado
Windows 7 avanzado
Whaleejaa Wha
 
Virtualizacion con vm ware
Virtualizacion con vm wareVirtualizacion con vm ware
Virtualizacion con vm ware
Whaleejaa Wha
 
Unity
UnityUnity
Ubuntu
UbuntuUbuntu
Tecnico windows
Tecnico windowsTecnico windows
Tecnico windows
Whaleejaa Wha
 
Tecnico hardware desde cero
Tecnico hardware desde ceroTecnico hardware desde cero
Tecnico hardware desde cero
Whaleejaa Wha
 
Soluciones pc desde cero
Soluciones pc desde ceroSoluciones pc desde cero
Soluciones pc desde cero
Whaleejaa Wha
 
Silverlight
SilverlightSilverlight
Silverlight
Whaleejaa Wha
 
Servicio tecnico notebooks
Servicio tecnico notebooksServicio tecnico notebooks
Servicio tecnico notebooks
Whaleejaa Wha
 
Seguridad pc desde cero
Seguridad pc desde ceroSeguridad pc desde cero
Seguridad pc desde cero
Whaleejaa Wha
 
Seguridad informatica
Seguridad informaticaSeguridad informatica
Seguridad informatica
Whaleejaa Wha
 
Routers y switches cisco
Routers y switches ciscoRouters y switches cisco
Routers y switches cisco
Whaleejaa Wha
 
Robotica
RoboticaRobotica
Robotica
Whaleejaa Wha
 
Redes wireless
Redes wirelessRedes wireless
Redes wireless
Whaleejaa Wha
 
Redes wifi
Redes wifiRedes wifi
Redes wifi
Whaleejaa Wha
 
Proteus vsm
Proteus vsmProteus vsm
Proteus vsm
Whaleejaa Wha
 
Produccion musical
Produccion musicalProduccion musical
Produccion musical
Whaleejaa Wha
 
Php avanzado
Php avanzadoPhp avanzado
Php avanzado
Whaleejaa Wha
 
Overclocking
OverclockingOverclocking
Overclocking
Whaleejaa Wha
 

More from Whaleejaa Wha (20)

Windows 7
Windows 7Windows 7
Windows 7
 
Windows 7 avanzado
Windows 7 avanzadoWindows 7 avanzado
Windows 7 avanzado
 
Virtualizacion con vm ware
Virtualizacion con vm wareVirtualizacion con vm ware
Virtualizacion con vm ware
 
Unity
UnityUnity
Unity
 
Ubuntu
UbuntuUbuntu
Ubuntu
 
Tecnico windows
Tecnico windowsTecnico windows
Tecnico windows
 
Tecnico hardware desde cero
Tecnico hardware desde ceroTecnico hardware desde cero
Tecnico hardware desde cero
 
Soluciones pc desde cero
Soluciones pc desde ceroSoluciones pc desde cero
Soluciones pc desde cero
 
Silverlight
SilverlightSilverlight
Silverlight
 
Servicio tecnico notebooks
Servicio tecnico notebooksServicio tecnico notebooks
Servicio tecnico notebooks
 
Seguridad pc desde cero
Seguridad pc desde ceroSeguridad pc desde cero
Seguridad pc desde cero
 
Seguridad informatica
Seguridad informaticaSeguridad informatica
Seguridad informatica
 
Routers y switches cisco
Routers y switches ciscoRouters y switches cisco
Routers y switches cisco
 
Robotica
RoboticaRobotica
Robotica
 
Redes wireless
Redes wirelessRedes wireless
Redes wireless
 
Redes wifi
Redes wifiRedes wifi
Redes wifi
 
Proteus vsm
Proteus vsmProteus vsm
Proteus vsm
 
Produccion musical
Produccion musicalProduccion musical
Produccion musical
 
Php avanzado
Php avanzadoPhp avanzado
Php avanzado
 
Overclocking
OverclockingOverclocking
Overclocking
 

Arrays in linux

  • 1. Arrays in Linux An array is a variable containing multiple values may be of same type or of different type. There is no maximum limit to the size of an array, nor any requirement that member variables be indexed or assigned contiguously. Array index starts with zero. 1. Declaring an Array and Assigning values In bash, array is created automatically when a variable is used in the format like, name[index]=value  name is any name for an array  index could be any number or expression that must evaluate to a number greater than or equal to zero.You can declare an explicit array using declare -a arrayname.
  • 2. $ cat arraymanip.sh #! /bin/bash Unix[0]='Debian' Unix[1]='Red hat' Unix[2]='Ubuntu' Unix[3]='Suse' echo ${Unix[1]} $./arraymanip.sh Red hat To access an element from an array use curly brackets like ${name[index]}. 2. Initializing an array during declaration
  • 3. Instead of initializing an each element of an array separately, you can declare and initialize an array by specifying the list of elements (separated by white space) with in a curly braces. Syntax: declare -a arrayname=(element1 element2 element3) If the elements has the white space character, enclose it with in a quotes. #! /bin/bash $cat arraymanip.sh declare -a Unix=('Debian' 'Red hat' 'Red hat' 'Suse' 'Fedora'); declare -a declares an array and all the elements in the parentheses are the elements of an array. 3. Print the Whole Bash Array
  • 4. There are different ways to print the whole elements of the array. If the index number is @ or *, all members of an array are referenced. You can traverse through the array elements and print it, using looping statements in bash. echo ${Unix[@]} # Add the above echo statement into the arraymanip.sh #./t.sh Debian Red hat Ubuntu Suse Referring to the content of a member variable of an array without providing an index number is the same as referring to the content of the first element, the one referenced with index number zero. 4. Length of the Bash Array We can get the length of an array using the special parameter called $#.
  • 5. ${#arrayname[@]} gives you the length of the array. $ cat arraymanip.sh declare -a Unix=('Debian' 'Red hat' 'Suse' 'Fedora'); echo ${#Unix[@]} #Number of elements in the array echo ${#Unix} #Number of characters in the first element of the array.i.e Debian $./arraymanip.sh 4 6 5. Length of the nth Element in an Array ${#arrayname[n]} should give the length of the nth element in an array. $cat arraymanip.sh #! /bin/bash Unix[0]='Debian'
  • 6. Unix[1]='Red hat' Unix[2]='Ubuntu' Unix[3]='Suse' echo ${#Unix[3]} # length of the element located at index 3 i.e Suse $./arraymanip.sh 4 6. Extraction by offset and length for an array The following example shows the way to extract 2 elements starting from the position 3 from an array called Unix. $cat arraymanip.sh Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux'); echo ${Unix[@]:3:2}
  • 7. $./arraymanip.sh Suse Fedora The above example returns the elements in the 3rd index and fourth index. Index always starts with zero. 7. Extraction with offset and length, for a particular element of an array To extract only first four elements from an array element . For example, Ubuntu which is located at the second index of an array, you can use offset and length for a particular element of an array. $cat arraymanip.sh #! /bin/bash Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
  • 8. echo ${Unix[2]:0:4} ./arraymanip.sh Ubun The above example extracts the first four characters from the 2nd indexed element of an array. 8. Search and Replace in an array elements The following example, searches for Ubuntu in an array elements, and replace the same with the word ‘SCO Unix’. $cat arraymanip.sh #!/bin/bash Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
  • 9. echo ${Unix[@]/Ubuntu/SCO Unix} $./arraymanip.sh Debian Red hat SCO Unix Suse Fedora UTS OpenLinux In this example, it replaces the element in the 2nd index ‘Ubuntu’ with ‘SCO Unix’. But this example will not permanently replace the array content. 9. Add an element to an existing Bash Array The following example shows the way to add an element to the existing array. $cat arraymanip.sh Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux'); Unix=("${Unix[@]}" "AIX" "HP-UX") echo ${Unix[7]}
  • 10. $./arraymanip.sh AIX In the array called Unix, the elements ‘AIX’ and ‘HP-UX’ are added in 7th and 8th index respectively. 10. Remove an Element from an Array unset is used to remove an element from an array.unset will have the same effect as assigning null to an element. $cat arraymanip.sh #!/bin/bash Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux'); unset Unix[3] echo ${Unix[3]}
  • 11. The above script will just print null which is the value available in the 3rd index. The following example shows one of the way to remove an element completely from an array. $ cat arraymanip.sh Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux'); pos=3 Unix=(${Unix[@]:0:$pos} ${Unix[@]:$(($pos + 1))}) echo ${Unix[@]} $./arraymanip.sh Debian Red hat Ubuntu Fedora UTS OpenLinux In this example, ${Unix[@]:0:$pos} will give you 3 elements starting from 0th index i.e 0,1,2 and ${Unix[@]:4} will give the elements from 4th index to the last index.
  • 12. And merge both the above output. This is one of the workaround to remove an element from an array. 11. Remove Bash Array Elements using Patterns In the search condition you can give the patterns, and stores the remaining element to an another array as shown below. $ cat arraymanip.sh #!/bin/bash declare -a Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora'); declare -a patter=( ${Unix[@]/Red*/} ) echo ${patter[@]} $ ./arraymanip.sh Debian Ubuntu Suse Fedora
  • 13. The above example removes the elements which has the patter Red*. 12. Copying an Array Expand the array elements and store that into a new array as shown below. #!/bin/bash Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux'); Linux=("${Unix[@]}") echo ${Linux[@]} $ ./arraymanip.sh Debian Red hat Ubuntu Fedora UTS OpenLinux 13. Concatenation of two Bash Arrays Expand the elements of the two arrays and assign it to the new array. $cat arraymanip.sh
  • 14. #!/bin/bash Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux'); Shell=('bash' 'csh' 'jsh' 'rsh' 'ksh' 'rc' 'tcsh'); UnixShell=("${Unix[@]}" "${Shell[@]}") echo ${UnixShell[@]} echo ${#UnixShell[@]} $ ./arraymanip.sh Debian Red hat Ubuntu Suse Fedora UTS OpenLinux bash csh jsh rsh ksh rc tcsh 14 It prints the array which has the elements of the both the array ‘Unix’ and ‘Shell’, and number of elements of the new array is 14.
  • 15. 14. Deleting an Entire Array unset is used to delete an entire array. $cat arraymanip.sh #!/bin/bash Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux'); Shell=('bash' 'csh' 'jsh' 'rsh' 'ksh' 'rc' 'tcsh'); UnixShell=("${Unix[@]}" "${Shell[@]}") unset UnixShell echo ${#UnixShell[@]} $ ./arraymanip.sh 0 After unset an array, its length would be zero as shown above.
  • 16. 15. Load Content of a File into an Array You can load the content of the file line by line into an array. #Example file $ cat logfile Welcome to thegeekstuff Linux Unix $ cat loadcontent.sh #!/bin/bash filecontent=( `cat "logfile" `) for t in "${filecontent[@]}"
  • 17. do echo $t done echo "Read file content!" $ ./loadcontent.sh Welcome to thegeekstuff Linux Unix Read file content! In the above example, each index of an array element has printed through for loop.