The Easy Way to get Array data in Shell-Script

Here is an easy way to get array data. Below, you will find a script and explains to get array data.

How to assign values to arrays

  • Here are two different ways to assign values to arrays. Those are one at a time and all at once.
  • You can assign values to an array from different sources, including wildcard expansion and program output.
  • Shell automatically detects if the array declares from the above two methods. Else, declare -a myarray statement is needed.

One at a time

numberarray[0]=zero

All at once

students=(Dave Jennifer Michael Alistair Lucy Richard Elizabeth)

Shell Script

You need to use dollar sign $ to get array data. The rate (@ ) says all the array values. The echo -en says two things. The -e tells to enable interpretation of backlash, and -n does not print the trailing newline after finishing the command.

$ vi studentarray.sh
#!/bin/bash

students=(Dave Jennifer Michael      # year 1
  Alistair Lucy Richard Elizabeth    # year 2 
  Albert Roger Dennis James Roy      # year 3
  Rory Jim Andi Elaine Clive         # year 4
  )

for name in ${students[@]}
do
  echo -en "$name "
done
echo

$ ./studentarray.sh
Dave Jennifer Michael Alistair Lucy Richard Elizabeth Albert Roger Dennis James Roy Rory Jim Andi Elaine Clive
$
Shell script output

Related

References

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.