Bash – Arrays

If you want to spent some time discovering CLI in Linux, you must study a lot about shell script, you can do magic with it.

An important thing while we are creating shell scripts is when we need to store data, this can happen using variables or arrays.

Let’s suppose that we need to store common information about a band into variables.

$ band_name = "Black Sabbath"
$ band_style = "Heavy Metal"
$ band_album = "Black Sabbath"
$ band_track = "1"

It’s obvious that if you have a lot of data to store, there’s not the easy way to do it, and it’s now that we can use a built-in in bash called array that will make this process easy.

You can create an array with an index and add a value into it, like the following example in a formal way.

syntax:
declare -a arrayname[indexnumber]=value
$ declare -a band=("Black Sabbath" "Heavy Metal" "Black Sabbath" "1")

The simple and more elegant way to create an array is the following.

  • Create an array.
$ band=("Black Sabbath" "Heavy Metal" "Black Sabbath" "1")

Now you can access all indexes and it’s values.

  • Display all the items in the array.
$ echo ${band[*]}
  • Display all indexes in the array.
$ echo ${!band[*]}
  • Display the number of items in the array.
$ echo ${#band[*]}
  • Length of an item in the array.
$ echo ${#band[0]}
  • Change or add items.
$ band[4]="Ozzy Osbourne"
$ band[1]="Rock 'n Roll"
  • Delete an array or items into it just use the unset built-in.
$ unset band[4]
$ unset band
  • Search a pattern and replace a value into an array.
$ echo ${band[@]/"Rock 'n Roll"/"Heavy Metal"}

 

 

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s