Bash/Shell Script Arrays

Bash/Shell array position starts form 0.

Define an array

$ names=( a b c d e f g h i j )

Print all values in array

$ echo “${names[@]}”

Output: a b c d e f g h i j

Print value form position 2 in array

$ echo “${names[0]}”

Output: a

Remove multiple values form array

$ unset names[2] names[4] names[6] names[8]

Remove a value form array

$ unset names[2]

Print length of array

$ echo ${#names[@]}

Print number of characters in first elements

$ echo ${#names}

Print number of characters in nth element

$ echo ${#names[1]}

Iterate through the all elements in array

$ for i in “${names[@]}”

   do

echo $i

    done

Output: prints all elements in array sequentially

Delete all elements form array

$ unset names

Load content of the file into an array

$ names=( `cat input.txt | tr ‘\n’ ‘ ‘` )

Add another element to existing array

$ names=( “${names[@]}” “k”)

-Sany

Leave a Reply

Fill in your details below or click an icon to log in:

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