Home > Mobile >  Cannot send command output into an array
Cannot send command output into an array

Time:09-16

I want to place each sysctl -a output line into an array:

TAB=($(sysctl -a)) 

It does not work; the resulting array contains the output split on any whitespace, instead of only on newlines:

[..]
NONE
net.netfilter.nf_log.5
=
NONE
net.netfilter.nf_log.6
=
NONE
net.netfilter.nf_log.7
=
NONE
net.netfilter.nf_log.8
[..]

I try:

while read -r line
   do
      TAB =("${line}") 
   done< <(sysctl -a) 

That does not work neither (same issue).

I try:

while IFS=$'\n' read -r line 
   do
      TAB =("${line}") 
   done< <(sysctl -a)

But still same output, same issue.

What's the correct method to have each line correctly placed in the array?

CodePudding user response:

One way - probably the easiest - is to use readarray (bash 4 needed).

readarray -t TAB < <(sysctl -a)

Test:

$ echo ${TAB[0]}
abi.vsyscall32 = 1

$ echo ${TAB[1]}
crypto.fips_enabled = 0

CodePudding user response:

You were close:

IFS=$'\n' TAB=($(sysctl -a)) 
# Usage example:
for x in "${TAB[@]}"
do
  echo $x
done
  • Related