I am currently working on a script that receives input from stdin, and then loads the input line by line into an array for further processing. Although the array works fine if I set the array name directly, I cannot get the array part to work properly when I attempt to use a variable as the array name, the code itself is below:
input=$(</dev/stdin)
# back up the field separator for later
OLDIFS=$IFS
# set the field separator to newline
IFS=$'\n'
# populate an array from that variable, as delimited by the IFS
lines=($input)
and this is what I have tried for setting the array name as a variable
arrayname="something"
eval $arrayname=($input)
but unfortunately when I go to run this, I get the following error:
./f.sh: line 53: syntax error near unexpected token `('
./f.sh: line 53: ` eval $arrayname=($input)'
having said all of this, I was wondering if anyone would know what I could do to make this work correctly? thanks!
Instead of playing with
IFS, which is useless in your case (even though I’m an avid fan ofIFS, I tend to only use it when necessary!), there’s a much better and much more efficient way of loading a file into an array. Incidentally, it is not very well-known: it’s the commandmapfile(typehelp mapfilein your terminal running bash for more info).Hence,
will read from standard input and store each line in an array
lines. This also stores the trailing new line character, so if you want to trim it, use the-toption:To print out the array, one line per entry, use:
(observe the quoting for
"${lines[@]}").Please note that using
evalis evil!Your main problem is to use a variable as an array name. bash doesn’t have what is called a pointer in other languages. Without using
eval, it will be difficult to use an array name stored in a variable (unless you use little trickeries). But, as I already said,evalis evil. Maybe you should spend a little more time thinking about your design, there’s probably another (better?) way to achieve what you’re trying to.