I agree to cookies for making this site function. By using this site, I agree to the Privacy Policy and Terms of Use.
Accept
HACKTORIAHACKTORIA
  • Home
  • Articles
    • CyberSecurity
    • OSINT
    • Networking
    • Programming
    • Software
    • Cloud
    • Crypto & Blockchain
    • Opinion
  • Monthly CTF
    • Challenges
      • The Mona Lisa Heist
      • Operation Mare Nostrum
      • Downtown Murderer
      • Operation Galaxios
      • Operation Brutus
      • Operation Runner
      • Operation Warthog
    • Storyline
      • April 2022 – Operation Galaxios
      • March 2022 – Operation Brutus
      • February 2022 – Operation Runner
      • January 2022 – Operation Warthog
    • Characters
    • Finishers 2022
    • Write-Ups
  • Practice
    • Fact Checking
      • Fact Checking 10
      • Fact Checking 9
      • Fact Checking 8
      • Fact Checking 7
      • Fact Checking 6
      • Fact Checking 5
      • Fact Checking 4
      • Fact Checking 3
      • Fact Checking 2
      • Fact Checking 1
    • Geolocation
      • Geolocation 32
      • Geolocation 31
      • Geolocation 30
      • Geolocation 29
      • Geolocation 28
      • Geolocation 27
      • Geolocation 26
      • Geolocation 25
      • Geolocation 24
      • Geolocation 23
      • Geolocation 22
      • Geolocation 21
      • Geolocation 20
      • Geolocation 19
      • Geolocation 18
      • Geolocation 17
      • Geolocation 16
      • Geolocation 15
      • Geolocation 14
      • Geolocation 13
      • Geolocation 12
      • Geolocation 11
      • Geolocation 10
      • Geolocation 9
      • Geolocation 8
      • Geolocation 7
      • Geolocation 6
      • Geolocation 5
      • Geolocation 4
      • Geolocation 3
      • Geolocation 2
      • Geolocation 1
    • Image Analysis
      • Image Analysis 16
      • Image Analysis 15
      • Image Analysis 14
      • Image Analysis 13
      • Image Analysis 12
      • Image Analysis 11
      • Image Analysis 10
      • Image Analysis 9
      • Image Analysis 8
      • Image Analysis 7
      • Image Analysis 6
      • Image Analysis 5
      • Image Analysis 4
      • Image Analysis 3
      • Image Analysis 2
      • Image Analysis 1
  • Videos
  • Art
  • About
    • Frank
    • Noureldin
    • Maria
    • Roxanna
    • Dipti
    • Joy
    • Oriana
    • Simone
    • Rudraksh
    • Amogh
    • Tony
Reading: Arrays Are Powerful In Bash
Share
Aa
HACKTORIAHACKTORIA
Aa
Search
  • Home
  • Articles
    • CyberSecurity
    • OSINT
    • Networking
    • Programming
    • Software
    • Cloud
    • Crypto & Blockchain
    • Opinion
  • Monthly CTF
    • Challenges
    • Storyline
    • Characters
    • Finishers 2022
    • Write-Ups
  • Practice
    • Fact Checking
    • Geolocation
    • Image Analysis
  • Videos
  • Art
  • About
    • Frank
    • Noureldin
    • Maria
    • Roxanna
    • Dipti
    • Joy
    • Oriana
    • Simone
    • Rudraksh
    • Amogh
    • Tony
Follow US
© 2022 HACKTORIA
HACKTORIA > Articles > Programming > Arrays Are Powerful In Bash
Programming

Arrays Are Powerful In Bash

Amoghavarsha
Amoghavarsha June 20, 2022
Updated 2022/06/30 at 6:02 PM
Share
SHARE
Contents
VariableArrayArray ModificationAssociative Array

“$” might symbolize dollars to many of you, but for bash users it’s the holy grail for retrieving stored data. Speaking of which, do you know what’s the common place to store a piece of data? A variable.

Variable

The name itself incurs that variable is something that could be varied. So is it like a chameleon that changes colors all the time? Not precisely, if you remember from the intro its a common place to store a piece of data. That’s right. Mathematically and computationally, a variable is something that stores or holds a piece of data or value.

You might have heard the term “place holder” and that’s exactly what a variable is. So how to store and retrieve information through variables?

place="World"
echo "Hello $place"

In the above code snippet, place is a variable and World is the value assigned to the variable. In the next line, the value assigned to the variable is retrieved through echo command. As aforementioned, “$” is the holy grail to retrieve stored value in bash. An important thing to note here is, “=” doesn’t mean variable name has a constant value, it just means that a value is assigned to a variable name.

Now the value of variable place could be varied.

place="Mars"
echo "Hello $place"

Now the value of variable has changed to Mars from World. Imagine a box where you could place an item and replace that item whenever you wish.

What if you want to store many pieces of data in a single box?

Array

Array is an ordered series of arrangement. Computationally, array holds multiple values, whereas a normal variable holds a single value. Array could also be defined as a special type of variable as it could hold more than one value.

A typical array consists of an array name and an index. Each index number associates with an element in the array.

Lets see how to create an array.

movies=('Primer' 'Inception' 'Enemy' 'Tenet')

Two things to keep in mind. Unlike other programming languages, bash arrays are not led by commas after every element but spaces. There is no space after array name(i.e, movies=), it’s followed by “=”. If there is a space followed by the array name, shell interprets the array name as a program to execute and “=” as the first parameter.

Now lets try to retrieve all the elements of the array.

As you could see in the above screenshot, you could retrieve the array elements in two ways: one using the @ symbol between the square brackets or using * symbol.

Here are some tips, you could remember @ by memorizing it like all and * is a wild card which signifies everything. The syntax of retrieving an array could look intimidating, so always remember “$” is the holy grail for retrieving information, array names are placed in between flower brackets {}, followed by special characters or numbers in square brackets.

Lets see how to retrieve an individual element of the array.

Index numbers in bash arrays starts with 0 (similar to most of the programming language, unlike R). So index 2 returns the value of Enemy.

Let’s see what happens when negative indices are used.

So the negative index number retrieves values from reverse order.

You could also assign elements to the array explicitly in three ways: Subscript Assignment, Index Assignment and assignment by name.

Subscript Assignment

movies=([4]='Ten cloverfield lane' [5]='Timecrimes') 

Index Assignment

movies[1]='Vanilla Sky'
movies[2]='Mr.Nobody'

Assignment by names

movies[zero]='Magnolia'

What if you want to print the elements from one particular index to another?

Here you are telling the array that from all its elements(@) , print from index 1 to index 3.

Here you are telling the array that from all its elements(@), start from index 1 and print all the following elements.

What if, you want to access the index numbers?

echo "${!movies[@]}"

The “!” symbol before array name helps to retrieve indices.

What if you want to see how many elements are there in an array?

echo "${#movies[@]}"

The “#” symbol before array name helps to retrieve number of elements.

How to retrieve specific information from an element in the array?

Here the information of zeroth element(Magnolia) is retrieved, starting from index 0 till index 2(not included).

What if you want to assign a sequence of numbers? You could do it manually but here’s a easy way to do it.

seq is a shell command that prints out sequence of numbers. In the above example, seq is placed in between ` `.

Now lets try to write a simple shell script from the above learnings.

#!/usr/bin/bash

tvshows=('Mr.Robot' 'Homeland' 'The Americans' 'Death Note' 'Erased')
for a in "${!tvshows[@]}"; do
  printf "${tvshows[$a]} has an index number of $a\n" 
done

Let’s save the code as lp.sh. Next lets make it executable – chmod +x lp.sh.

When the program is executed, you get the above result.

Array Modification

Lets create a new array.

names=('Luther' 'Ambrose' 'Reddington' 'Mare')

To change the value of index 2 you could do the following.

names[2]=’Carrie’

What if, you want to append values by adding more elements to the array?

What if, you want to add an element at a particular index position?

What if you want to delete an element?

Here, unset is a shell builtin.

What if you want to merge two arrays?

Lets create another array.

surnames=('Dexter' 'Hannibal' 'Broody' 'Dan' 'Gordan' 'Steve')

What if you want to delete an array?

unset <array_name>

Associative Array

An associative array is an array that stores string value as an index. It could be declared and used in a bash script. This feature was added in bash 4. To be sure, just check your bash version.

Declaring an associative array is easy, here’s the syntax.

declare -A <array_name>

Lets declare an associative array and initialize some elements.

Like in normal array, if you want to access an element of the array, use the following syntax.

If you want to list the indices of the associative array, do the following.

Now lets try to write a simple script to print the indices(keys) and values of the associative array.

Here’s a catch, what if you want to display the indices in an alphabetic order?

To reverse it, use –reverse flag.

Well that’s it for today. Do practice arrays; because they are powerful! Show some love by sharing and commenting below the article. You can find more about me here.

TAGGED: bash, bashscripting, coding, linux, programming, scripting

Sign Up For our Weekly Digest

Receive a weekly digest of everything new on Hacktoria

By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Amoghavarsha June 20, 2022
Amoghavarsha
Posted by Amoghavarsha
Follow:
Freelancer, writer, OSINT consultant and cyber security enthusiast, geopolitics nut, movie buff, bibliophile, selective extrovert.
Leave a comment

Leave a Reply Cancel reply

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

About Us

Hacktoria is a passion project run by volunteers.  We aim to create something we enjoy making that provides value to our readers, viewers and players. Our backgrounds vary from Information Technology, Cybersecurity to Data and Law.

Capture the Flag

We provide a Monthly Story Based Capture the Flag exercise. Players solve tasks using OSINT, Hacking, Social Engineering and Cryptographic skills to complete story driven missions. The winner of each competition is written into the fictional story. Participants receive a certificate of completion.

We also offer Practice Labs in various categories. These are intended to improve your investigative skills and provide a good dose of challenge and entertainment.

Articles & Videos

Besides CTF Exercises, our Editorial Team writes Articles about Cybersecurity, OSINT and Technology. We also host a YouTube channel that provides informative content and CTF material. This channel is hosted by Tony, aka “CyberVikingUK“.

HACKTORIAHACKTORIA
Follow US

© 2022 HACKTORIA - Capture the Flag Exercises & Cybersecurity, OSINT and Technology Articles

  • Sitemap
  • Privacy & Disclaimer
Join Us!

Subscribe to our weekly digest!

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?