bash shell script declaring/creating arrays

Home -> Programming -> Shell script -> Bourne shells

40536 views

From the computer of: qmchenry (334 recipes)
Created: Aug 30, 2004


1 comments:
View all comments

Add a comment

Add to:
Add to stumbleuponAdd to del.icio.usDigg itAdd to FURL

The use of array variable structures can be invaluable. This recipe describes several methods for delcaring arrays in bash scripts.

The following are methods for declaring arrays:

names=( Jennifer Tonya Anna Sadie )


This creates an array called names with four elements (Jennifer, Tonya, Anna, and Sadie).

names=( "John Smith" "Jane Doe" )


This creates two array elements, each containing a space.

colors[0] = red
colors[3] = green
colors[4] = blue


This declares three elements of an array using nonsequential index values and creates a sparse array (there are no array elements for index values 1 or 2).

filearray=( `cat filename | tr '\n' ' '`)


This example places the contents of the file filename into an array. The tr command converts newlines to spaces so that multiline files will be handled properly.

names=( "${names[@]}" "Molly" )


This example adds another element to an existing array names.

If anyone has other techniques for creating or adding to arrays, add a comment to this recipe and share the wealth!

Subscribe to the Tech-Recipes Newsletter

You can get tips like this delivered in your email every week!

Enter your Email

We will never, ever sell your email address or spam you.




1 Recipe comments: View comments

bash shell script declaring/creating arrays by Anonymous



Related recipes:

  bash shell script accessing array variables
  Bourne/bash shell script functions
  Bourne/bash shell script for loop syntax
  Bourne/bash shell scripts: case statement
  Determine if a file is writable by a Bourne script user
  Determine if file exists in a Bourne/bash shell script
  bash shell script iterate through array values
  Bourne/bash shell scripts: if statement syntax
  Determine if a file is readable by current Bourne shell script user
  Bourne/bash shell script: while loop syntax

 

Sponsored links

 

Login

Nickname

Password

Don't have an account yet? You can create one. As a registered user you have some advantages like theme manager, comments configuration and post comments with your name.