How can an array be accessed from within another function?

Here is an example of some code. editarray can not seem to access values of the array from outside of the writetofile function. Is there any way to change the scope of the array?

#!/bin/sh
writetofile()
{
templine=`cat /dev/stdin`
export templine
echo "templine is: $templine"
var1=$(echo $templine | gawk '{print $1}')
var2=$(echo $templine | gawk '{print $2}')
var3=$(echo $templine | gawk '{print $3}')
var4=$(echo $templine | gawk '{print $4}')
var5=$(echo $templine | gawk '{print $5}')
echo $var1" "$var2" "$var3" "$var4" "$var5" "
export var1 var2 var3 var4 var5
arrayfunction
#some commands to edit standard input
}
arrayfunction()
{
echo "writing to array"
array[0]=$var1
array[1]=$var2
array[2]=$var3
array[3]=$var4
array[4]=$var5
}
editarray()
{
echo "editing array"
echo "==========Array==Output========="
echo ${array[@]}
echo "==========Finished==Output======"
echo "writing to file"
#call array at index and assign value
}
#main
echo "input this to be parsed and placed into an array" | writetofile
editarray

hi,

that's silly coding :(

var="input this to be parsed and placed into an array"
array=( $var )
printf '%s\n' "${array[@]}"

that's all.

an array is like any other variable: if not defined as local, they're global (exept associative arrays which need to be declared, and declared as global).

$ myFunc() { array=( a b c d );}
$ myFunc_2() { printf '%s\n' "${array[@]}" ;}
$ myFunc
$ myFunc_2
a
b
c
d

I didn't know that shell arrays would take input like that. Would have saved me a lot of trouble with gawks if I had known.

This seems to work now. Thanks :)

myFunc() { myFunc_2 ;}
myFunc_2() { array=( a b c d ); }
myFunc_3() { printf '%s\n' "${array[@]}" ; }
myFunc
myFunc_3

Just out of curiousity, why doesn't editarray, from the original code posted, output anything from #main but will from within the function writetofile?

that's because of the pipe which creates a subshell outisde of which variables are not available.

like this:

$ echo "value" | read var
$ echo ${var:-empty}
empty
$ echo "value" | { read var; echo "${var:-empty}";}
value

re-write the function to take arguments instead of reading from stdin.

by the way, sh doesn't have arrays.
/bin/sh is probably an alias to bash; so you have to adapt your shebang to reflect the real shell you're using.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.