linux tools shell script.. computer science

profileSingpran
ShellProgramming-Arrays51.ppt

ARRAYS

  • Array is a variable which contains multiple values may be of same type or different type since by default in shell script everything is treated as a string.
  • An array is zero-based ie indexing start with 0.

*

HOW TO DECLARE ARRAY IN SHELL SCRIPTING?

1. Indirect Declaration

Assign a value in a particular index of Array Variable. No need to first declare

ARRAYNAME[INDEXNR]=value

2. Explicit Declaration

declare -a ARRAYNAME

3. Compound Assignment

ARRAYNAME=(value1 value2 .... valueN)

*

ARRAYS IN BASH

  • bash has two types of arrays: one-dimensional indexed arrays and associative arrays •
  • Any variable can be used as a 1D array – Identified as var[index]

$x=24

$ echo ${x[0]}

  • Indexed arrays

• Index array need not be declared though they can be using the command declare -a

• You can also declare arrays of any size by

declare -a color[3]

with the elements indexed from 0 to 2 –

In reality, the index above is ignored

– You can simply add more elements to it by assigning an element with a new index

*

ACCESSED BY AN INDEX

– Index starts at 0

– Index can be any positive integer, up to 599147937791

– Arithmetic expressions are supported in index

• Values are assigned by

var[index]=value

• Examples

color[1]="red"

color[2]="green"

color[0]="blue"

– Values need not be assigned in any specific order

Another way to assign values, known as compound statement, is

color=([2]=green [1]=red [0]=blue)

*

If you specify the elements in order, you can specify them as

color=(red blue green)

• The above values can be accessed by

for i in 0 1 2

do

echo ${color[$i]}

done

– You must use the curly braces to access array elements; otherwise, you’ll just get the first array element and the subscript

*

*

IFS: internal field separator

*

*

*

*

*

TO COUNT LENGTH OF ARRAY

*

COLOR=(RED BLUE GREEN)

*

COLOR=(RED BLUE GREEN)

*

COLOR=(RED BLUE GREEN)

*

The contents of the colors array is not change, only the output

*

BASH ASSOCIATIVE ARRAY EXAMPLES

*

*

(foo=bar baz=quux corge=grault)

*

QUOTING KEYS

*

$ k=plugh

$ MYMAP['$K']=xyzzy

$ echo ${MYMAP[plugh]}

$ echo ${MYMAP['$K']}

xyzzy

*

ASSOCIATIVEARRAYS

*

Use:

printf instead of print

([apple red] [banana yellow] [grape purple])

LOOPING

*

Use double quotation “

*

*

ECHO

*

*

${MYMAP[${KEYS[$I]}]}

KEYS=(“foo a” “baz b)

SCOPE

*