views:

1125

answers:

6

how to create a array in unix shell programming ?

and i have to excute the program still i press a key similar to do u want to continue option

A: 

As to your question about creating an array in a shell script, I haven't personally done it, but I found the following:

http://www.linuxtopia.org/online%5Fbooks/advanced%5Fbash%5Fscripting%5Fguide/arrays.html

Interesting how accessing elements within an array requires such a different notation.

jeremyosborne
A: 

You can try of the following type :

#!/bin/bash
 declare -a arr

 i=0
 j=0

  for dir in $(find /home/rmajeti/programs -type d)
   do
        arr[i]=$dir
        i=$((i+1))
   done


  while [ $j -lt $i ]
  do
        echo ${arr[$j]}
        j=$((j+1))
  done
Roopesh Majeti
breaks on directory names with spaces. use a while read loop of change IFS to take care of that.
+2  A: 
#!/bin/bash

# define a array, space to separate every item
foo=(foo1 foo2)

# access
echo ${foo[1]}

# add or changes
foo[0]=bar
foo[2]=cat
foo[1000]=also_OK

You can read the ABS "Advanced Bash-Scripting Guide"

NjuBee
+2  A: 

in bash, you create array like this

arr=(one two three)

to call the elements

$ echo ${arr[0]}
one
$ echo ${arr[2]}
three

to ask for user input, you can use read

read -p "Enter your choice: " choice

is that what you are asking for.?

A: 

The Bourne shell and C shell don't have arrays, IIRC.

In addition to what others have said, in Bash you can get the number of elements in an array:

elements=${#arrayname[@]}

and do slice-style operations:

array=(apple banana cherry)
echo ${arrayname[@]:1}                   # yields "banana cherry"
echo ${arrayname[@]: -1}                 # yields "cherry"
echo ${arrayname[${#arrayname[@]}-1]}    # yields "cherry"
echo ${arrayname[@]:0:2}                 # yields "apple banana"
echo ${arrayname[@]:1:1}                 # yields "banana"
Dennis Williamson
A: 

In ksh you do it:

set -A array element1 element2 elementn

# view the first element
echo ${array[0]}

# Amount elements (You have to substitute 1)
echo ${#array[*]}

# show last element
echo ${array[ $(( ${#array[*]} - 1 )) ]}