Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Shell Scripting
  • Kali Linux
  • Ubuntu
  • Red Hat
  • CentOS
  • Docker in Linux
  • Kubernetes in Linux
  • Linux interview question
  • Python
  • R
  • Java
  • C
  • C++
  • JavaScript
  • DSA
Open In App
Next Article:
Conditional Statements | Shell Script
Next article icon

Array Basics in Shell Scripting | Set 1

Last Updated : 08 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Consider a situation if we want to store 1000 numbers and perform operations on them. If we use a simple variable concept then we have to create 1000 variables and perform operations on them. But it is difficult to handle a large number of variables. So, it is good to store the same type of values in the array and then access via index number.

Understanding Arrays in Shell Scripting

An array is a structured arrangement of similar data elements. Within shell scripting, an array is a variable that holds multiple values, whether they are of the same type or different types. It’s important to note that in shell scripting, everything is treated as a string. Arrays adhere to a zero-based index, which signifies that indexing initiates from 0.

How to Declare Array in Shell Scripting?

Arrays can be declared in a shell script using various approaches:

1. Indirect Declaration

In this method, you assign a value to a specific index of the array variable. There’s no need to declare the array beforehand.

ARRAYNAME[INDEXNR]=value

2. Explicit Declaration

With explicit declaration, you first declare the array and then assign values to it.

declare -a ARRAYNAME

3. Compound Assignment

This method involves declaring the array along with its initial set of values. You can later add additional values to the array.

ARRAYNAME=(value1 value2  .... valueN)

Alternatively, you can use index numbers to assign values explicitly:

ARRAYNAME=([1]=10 [2]=20 [3]=30)

Printing Array Values in Shell Script:

To display array elements, you have several options:

Here is a `array_test.sh`script explaining multiple options. (You can create script with any name)

#!/bin/bash

# To declare a static Array
arr=(“Jayesh” “Shivang” “1” “Vipul” “Nishant” “2”)

# To print all elements of the array
echo “All elements of the array:”
echo “${arr[@]}”
echo “${arr[*]}”

# To print the first element
echo “The first element:”
echo “${arr[0]}”

# To print a selected index element
selected_index=3
echo “Selected index element at index $selected_index:”
echo “${arr[$selected_index]}”

# To print elements from a particular index
echo “Elements from a particular index:”
echo “${arr[@]:2}” # Prints elements starting from index 2
echo “${arr[*]:2}” # Prints elements starting from index 2

# To print elements in a range
echo “Elements in a range:”
echo “${arr[@]:1:3}” # Prints elements from index 1 to 3
echo “${arr[*]:1:3}” # Prints elements from index 1 to 3

Explanation:

  1. Array Declaration: An array named arr is declared, containing six elements. These elements are strings: “prakhar”, “ankit”, “1”, “rishabh”, “manish”, and “abhinav”.
  2. Printing All Elements:
    • echo "All elements of the array:": A message is printed to indicate that all elements of the array are being displayed.
    • ${arr[@]}: This syntax is used to print each element of the array separately. It displays all elements in the array.
    • ${arr[*]}: Similar to the previous line, this syntax prints all elements of the array as a single string.
  3. Printing the First Element:
    • echo "The first element:": A message is printed to indicate that the first element of the array is being displayed.
    • ${arr[0]}: This syntax retrieves and displays the first element of the array. In Bash, array indexing starts at 0.
  4. Printing a Selected Index Element:
    • selected_index=3: A variable named selected_index is assigned the value 3. This variable represents the desired index in the array.
    • echo "Selected index element at index $selected_index:": A message is printed to indicate the selected index.
    • ${arr[$selected_index]}: Using the value stored in selected_index, this syntax retrieves and displays the element at the specified index (index 3 in this case).
  5. Printing Elements from a Particular Index:
    • echo "Elements from a particular index:": A message is printed to indicate that elements from a specific index are being displayed.
    • ${arr[@]:2}: This syntax extracts and displays all elements starting from index 2 in the array. It prints each element separately.
    • ${arr[*]:2}: Similar to the previous line, this syntax displays the elements as a single string, starting from index 2.
  6. Printing Elements in a Range:
    • echo "Elements in a range:": A message is printed to indicate that elements within a specified range are being displayed.
    • ${arr[@]:1:3}: This syntax extracts and displays elements starting from index 1 up to index 3 (inclusive). It prints each element separately.
    • ${arr[*]:1:3}: Similar to the previous line, this syntax displays the extracted elements as a single string.
457

Array Basics

Here is a `array_test2.sh` script with few other examples. (you can create script with any name)

#!/bin/bash

# Declare a static Array
arr=(“Jayesh” “Shivang” “1” “rishabh” “Vipul” “Nishtan”)

# Count the length of a particular element in the array
element_length=${#arr[2]}
echo “Length of element at index 2: $element_length”

# Count the length of the entire array
array_length=${#arr[@]}
echo “Length of the array: $array_length”

# Search in the array
search_result=$(echo “${arr[@]}” | grep -c “Jayesh”)
echo “Search result for ‘Jayesh’: $search_result”

# Search and replace in the array
replaced_element=$(echo “${arr[@]/Shivang/SHIVANG}”)
echo “Array after search & replace: ${replaced_element[*]}”

# Delete an element in the array (index 3)
unset arr[3]

echo “Array after deletion: ${arr[*]}”

Explanation:

  • Array Declaration:
    • An array named arr is declared, containing six elements.
    • These elements are strings: “Jayesh”, “Shivang”, “1”, “rishabh”, “Vipul”, and “Nishtan”.
  • Printing Element Length:
    • The length of the element at index 2 of the array is calculated using ${#arr[2]}.
    • This length is stored in the variable element_length.
  • Printing Array Length:
    • The length of the entire array is calculated using ${#arr[@]}.
    • This length is stored in the variable array_length.
  • Searching in the Array:
    • The grep command is used to search for occurrences of the string “Jayesh” in the array ${arr[@]}.
    • The -c flag is used to count the number of occurrences.
    • The count is stored in the variable search_result.
  • Searching and Replacing in the Array:
    • A search and replace operation is performed on the array ${arr[@]}.
    • The string “Shivang” is replaced with “SHIVANG”.
    • The updated array is stored in the variable replaced_element.
  • Deleting an Element from the Array:
    • The unset command is used to delete the element at index 3 (which is “rishabh”) from the array ${arr[@]}.
  • Printing All Elements:
    • The message “All elements of the array:” is echoed.
    • ${arr[@]} syntax is used to print each element of the array separately. This displays all elements in the array.

458

Array Basics

Conclusion

In this article we discussed about utility of arrays in shell scripting. It underlines how arrays efficiently handle a multitude of values, replacing numerous variables. The concept of array declaration is explained through three methods: indirect, explicit, and compound assignment. The article further illustrates printing array elements using practical script examples. This discussion not only demystifies array usage but also underscores its significance in managing and manipulating data within shell scripts.



Next Article
Conditional Statements | Shell Script

P

prakhargvp
Improve
Article Tags :
  • Linux-Unix
  • Shell Script

Similar Reads

  • Introduction to Linux Shell and Shell Scripting
    If we are using any major operating system, we are indirectly interacting with the shell. While running Ubuntu, Linux Mint, or any other Linux distribution, we are interacting with the shell by using the terminal. In this article we will discuss Linux shells and shell scripting so before understandi
    7 min read
  • Introduction to Shell Scripting

    • How to Create a Shell Script in linux
      Shell is an interface of the operating system. It accepts commands from users and interprets them to the operating system. If you want to run a bunch of commands together, you can do so by creating a shell script. Shell scripts are very useful if you need to do a task routinely, like taking a backup
      7 min read

    • Different Shells in Linux
      SHELL is a program which provides the interface between the user and an operating system. When the user logs in OS starts a shell for user. Kernel controls all essential computer operations, and provides the restriction to hardware access, coordinates all executing utilities, and manages Resources b
      5 min read

    Basic Shell Commands in Linux

    • Basic Shell Commands in Linux: Complete List
      Anyone using Linux should become an expert in the essential shell commands, as they form the backbone of working with the Linux terminal. These commands enable you to navigate the system, manage files, handle processes, and configure settings effectively. The Linux shell serves as an interface for u
      5 min read

    • Linux Directory Structure
      Prerequisite: Linux File Hierarchy Structure In Linux/Unix operating system everything is a file even directories are files, files are files, and devices like mouse, keyboard, printer, etc are also files. Here we are going to see the Directory Structure in Linux. Types of files in the Linux system.
      5 min read

    • Input Output Redirection in Linux
      In Linux, whenever an individual runs a command, it can take input, give output, or do both. Redirection helps us redirect these input and output functionalities to the files or folders we want, and we can use special commands or characters to do so. For example, if we run the "date" command, it giv
      4 min read

    Variables and Data Types

    • Shell Scripting - Shell Variables
      A shell variable is a character string in a shell that stores some value. It could be an integer, filename, string, or some shell command itself. Basically, it is a pointer to the actual data stored in memory. We have a few rules that have to be followed while writing variables in the script (which
      6 min read

    • Shell Scripting - Rules for Naming Variable Name
      Variables are quite important in any script or program, so we need to understand what is the convention to name these variables. There are certain rules and standards to keep in mind while giving names to the variables in Shell scripting. In this article, we will discuss and list down all the rules
      4 min read

    • String Manipulation in Shell Scripting
      String Manipulation is defined as performing several operations on a string resulting change in its contents. In Shell Scripting, this can be done in two ways: pure bash string manipulation, and string manipulation via external commands. Basics of pure bash string manipulation: 1. Assigning content
      4 min read

    • Array Basics in Shell Scripting | Set 1
      Consider a situation if we want to store 1000 numbers and perform operations on them. If we use a simple variable concept then we have to create 1000 variables and perform operations on them. But it is difficult to handle a large number of variables. So, it is good to store the same type of values i
      6 min read

    Control Structures

    • Conditional Statements | Shell Script
      Conditional Statements: There are total 5 conditional statements which can be used in bash programming if statement if-else statement if..elif..else..fi statement (Else If ladder) if..then..else..if..then..fi..fi..(Nested if) switch statement Their description with syntax is as follows: if statement
      3 min read

    • Looping Statements | Shell Script
      Looping Statements in Shell Scripting: There are total 3 looping statements that can be used in bash programming  Table of Content `while` statement in Shell Script in Linux`for` statement in Shell Script in Linux`until` statement in Shell Script in LinuxExamples of Looping StatementsTo alter the fl
      10 min read

    • Break and Continue Keywords in Linux with Examples
      Both “break” and “continue” are used to transfer control of the program to another part of the program. It is used within loops to alter the flow of the loop and terminate the loop or skip the current iteration. break The break statement is used to terminate the loop and can be used within a while,
      3 min read

    Functions and Script Organization

    • Shell Scripting - Functions and it's types
      Shell scripting is a powerful tool used to automate tasks in Unix-like operating systems. A shell serves as a command-line interpreter, and shell scripts often perform file manipulation, program execution, and text output. Here, we'll look into functions in shell scripting, exploring their structure
      5 min read

    • How To Pass and Parse Linux Bash Script Arguments and Parameters
      Parsing and Passing of Arguments into bash scripts/ shell scripts is quite similar to the way in which we pass arguments to the functions inside Bash scripts. We'll see the actual process of passing on the arguments to a script and also look at the way to access those arguments inside the script. Pa
      7 min read

    Input And Output

    • Shell Scripting - Standard Input, Output and Error
      Working on Linux applications we have several ways to get information from outside and to put it inside: command line args, environment variables, files. All of these sources are legal and good. But it has a finite size. Another way to establish communication is standard streams: input stream (stdin
      7 min read

    • Shell Script to Perform Operations on a File
      Most of the time, we use shell scripting to interact with the files. Shell scripting offers some operators as well as some commands to check and perform different properties and functionalities associated with the file. For our convenience, we create a file named 'geeks.txt' and another .sh file (or
      5 min read

    Command-Line Arguments and Options

    • Shell Script to Demonstrate Special Parameters With Example
      Here, we are going to see what are the special Parameters of the shell script. Before that first, let's understand what is parameters in the shell. The parameter is the entity that stores the value. The variables are the parameters that are defined by the user to use in that specific shell script. A
      5 min read

    Error Handling and Debugging

    • User Space Debugging Tools in Linux
      In this article, we will discuss debugging tools in Linux. Debugging Tools are those programs that allow us to monitor, control, and correct other program's error while they execute. Some of the debugging tools are as follows:- 'print Statement'Querying (/proc, /sys etc)Tracing (strace/ltrace)Valgri
      3 min read

    • Shell Scripting - System Logging
      Shell scripting is a way of automating tasks and operations on a computer system by writing scripts and programs in a shell or terminal environment. These scripts can run commands, access system resources, and process data. Shell scripts are often used to automate repetitive tasks, such as backups,
      9 min read

    Regular Expressions

    • How to Use Regular Expressions (RegEx) on Linux
      Regexps are acronyms for regular expressions. Regular expressions are special characters or sets of characters that help us to search for data and match the complex pattern. Regexps are most commonly used with the Linux commands:- grep, sed, tr, vi. The following are some basic regular expressions:
      5 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences