Bash Basics Series # 5: Using Arrays in Bash

 Su Su Su Su
two hundred and forty-four
2024-01-02


In the previous part of this series, you learned about variables. A variable can have a single value.

There can be multiple values inside an array. This makes things easier when you have to deal with multiple variables at once. You don't have to store values in new variables.

Therefore, do not declare five variables like this:

 distro1=Ubuntu distro2=Fedora distro3=SUSE distro4=Arch Linux distro5=Nix

You can initialize all of them in a single array:

 distros=(Ubuntu Fedora SUSE "Arch Linux" Nix)

Unlike some other programming languages, you do not use commas as array element separators.

That's very good. Let's see how to access array elements.


Access array elements in Bash

Access array elements using indexes (positions in the array). To access array elements at index N, use:

 ${array_name[N]}

Like most other programming languages, arrays in the Bash shell start at index 0. This means that the index of the first element is 0, the index of the second element is 1, and the index of the nth element is n-1.

So if you want to print SUSE, you will use:

 echo ${distros[2]}

🚧 $ There cannot be any spaces after {or before}. You can't use it like ${array [n]}.


Access all array elements at once

Suppose you want to print all the elements of the array.

You can use echo ${array [n]} one by one, but this is really unnecessary. There is a better and simpler way:

 ${array[*]}

This will provide you with all array elements.


Get the array length in Bash

How do I know how many elements are in an array? There is a special method to obtain the array length in Bash:

 ${#array_name[@]}

It's that simple, right?


Add array elements to Bash

If you must add other elements to the array, use the+=operator to append the elements to the existing array in Bash:

 array_name+=("new_value")

This is an example:

🚧 It is important to use () when appending elements.

You can also use indexes to set elements anywhere.

 array_name[N]=new_value

But remember to use the correct index number. If you use it on an existing index, the new value replaces the element.


If you use the "out of bounds" index, it will still be added after the last element. For example, if the array length is 6 and you try to set a new value at index 9, the value will still be added to the seventh position (index 6) as the last element.


Delete Array Elements

You can use the shell's built-in unset to delete array elements by providing the index number:

 unset array_name[N]

This is an example. I deleted the fourth element of the array.

You can also delete the entire array by unset:

 unset array_name

There are no strict data type rules in Bash. You can create an array that contains both integers and strings.


Practice time

Let's practice what you have learned about Bash arrays.

Exercise 1: Create a Bash script that contains an array of five best Linux distributions. Print them all.

Now, replace the middle choice with "Hannah Montanna Linux".

Exercise 2: Create a Bash script that accepts three numbers provided by the user and prints them in reverse order.

Expected output:

 Enter three numbers and press enter 12 23 44 Numbers in reverse order are: 44 23 12

I hope you enjoy learning Bash Shell scripts through this series. In the next chapter, you will learn how to use if else. Stay tuned.


Special statement: If there is no explanation, the articles are original. Please indicate the address of this article when reprinting. Thank you for your cooperation!

This site is only for sharing information, not for recommendation. All content only represents personal views. Readers are at their own risk. If you have to put the risk on Susu's head, don't be so cruel, OK?
This website guarantees that your personal information will not be disclosed to any third party through this website within the legal scope.
All network products cannot guarantee the same access experience for any broadband in any region of China at any time. Those who claim that a computer room will never take a breath are either liars or hehe
Any IDC has the possibility of going bankrupt and running away. Backup is always the best choice. The server is also a machine. If you don't backup frequently, you are extremely irresponsible for yourself

Join group 1: 569839985

IDC is welcome to submit preferential information or test prototype. Please send the information to admin#138vps.com Susu does not guarantee that it will be released.

However, IDC should pay attention to the following:
No official homepage or contact information is available;
Those who once went bankrupt and ran away will not be released within 6 months after being reopened;
From this day (July 18, 2016), we will not accept any form of free sponsorship and VPS gifts, any contribution to the evaluation report, any paid release and paid deletion comments. If it is necessary for IDC to submit a test prototype, please delete it after 7 days.
Notice
Welcome to join the qq group: five hundred and sixty-nine million eight hundred and thirty-nine thousand nine hundred and eighty-five
This site sincerely exchange friendship links. Add the friendship link on your website and send an email to admin # 138vps.com. Su Su will review it by herself and launch your friendship link within a week.
Requirements: Baidu should have a weight of 1, and the number of entries should not be less than 1000.
Please try your best to use PayPal for transactions. PayPal's fund protection policy takes more care of buyers.
Annual explosive