0

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
2
Contributors
4
Replies
28
Views
3 Years
Discussion Span
Last Post by Watael
0

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

Edited by Watael

0

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

Edited by duke.tim

0

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

0

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.

Edited by Watael

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.