loader

Array

Array is a data structure consist multiple elements based on key pair basis and the element is accessible via a key index number. Unlike most of the programming languages, Bash array elements don’t have to be of the same data type. You can create an array that contains both strings and numbers.

How to declare an Array in Bash:

				
					
amir@server:~$workdays=("Monday" "Tuesday"  "Wednesday" "Thursday" "Friday")
				
			

However, there are some other ways for declare an array but this way is most useful.

How to access an array in Bash”

				
					amir@server:~$echo ${workdays[*]}
amir@server:~$echo ${workdays[@]}
				
			

*  and @ are special character that you can use in bash for printing all value in array.

Also, you can access to one element if array by this way:

				
					amir@server:~$echo ${workdays[2]}
				
			

you should be aware that indexing starts from 0.

Adding New Elements to Array:

				
					amir@server:~$workdays+=("Saturday")
				
			

Update Array Elements:

				
					amir@server:~$workdays[0]="sunday"
				
			

Delete An Array Element:

				
					amir@server:~$unset workdays[0]
				
			

How to get an Array size:

				
					amir@server:~$echo ${#workdays[*]}
				
			

Loop through the array:

				
					amir@server:~$workdays=("Monday" "Tuesday"  "Wednesday" "Thursday" "Friday")
>for i in {0..4}
>do
>echo The company workdays are:${ workdays[i]}
>done

				
			

Leave a Reply

Your email address will not be published. Required fields are marked *