Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding to an array in ksh

Status
Not open for further replies.

columb

IS-IT--Management
Feb 5, 2004
1,231
EU
I have an array in ksh script and I want to extend it
When I try a test script
Code:
#!/bin/ksh 
 
set -A arr one two three
index=0
while [[ $index -lt ${#arr[*]} ]]
do
  echo ${arr[$index]}
  (( index += 1 ))
done
set -A arr ${arr[*]} four
index=0
while [[ $index -lt ${#arr[*]} ]]
do
  echo ${arr[$index]}
  (( index += 1 ))
done
it works exactly as I would wish. However, if the array members have spaces in them i.e.
Code:
#!/bin/ksh 
 
set -A arr "part one" "part two"  "part three"
index=0
while [[ $index -lt ${#arr[*]} ]]
do
  echo ${arr[$index]}
  (( index += 1 ))
done
set -A arr ${arr[*]} "part four"
index=0
while [[ $index -lt ${#arr[*]} ]]
do
  echo ${arr[$index]}
  (( index += 1 ))
done
then the first three members are re-interpreted as six separate items when the array is rebuilt to add the fourth element. and the output looks like
Code:
part one
part two
part three
part
one
part
two
part
three
part four

There must be a better way of adding a new member to a ksh array but the IBM web pages don't really help. Any pointers please?

Ceci n'est pas un signature
Columb Healy
 
I sorted it out myself (after stumbling across the O'Rielly book)
The code should look like
Code:
#!/bin/ksh
 
set -A arr "part one" "part two"  "part three"
index=0
while [[ $index -lt ${#arr[*]} ]]
do
  echo ${arr[$index]}
  (( index += 1 ))
done
 
arr[${#arr[*]}]="part four"
index=0
while [[ $index -lt ${#arr[*]} ]]
do
  echo ${arr[$index]}
  (( index += 1 ))
done

Ceci n'est pas un signature
Columb Healy
 
Alternatively you could have used set -A arr "${arr[@]}" "part four".

Annihilannic.
 
so the difference between ${arr[*]} and ${arr[@]} resembles the difference between $* and $@

Thanks Annihilannic

Ceci n'est pas un signature
Columb Healy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top