0

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?

2
  • See mywiki.wooledge.org/BashFAQ/… Commented Sep 15, 2021 at 12:01
  • 1
    @LéaGris, the accepted solution on that question will split the command output on whitespace which is the problem achille is having. Commented Sep 15, 2021 at 13:57

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

5 Comments

Without Bash4 you just use IFS=$'\n' read -r -d '' -a TAB < <(sysctl -a)
.@cornuz: Nice tip! I can make my way with this. I am just wondering if there is a way to fecth each element from the array without specifying an index - echo ${TAB[index]} -, so that I can get rid of a counter in my snippet.
@achille You probably mean for x in "${TAB[@]}"; do echo ${x}; done, like in user1934428's answer? Although, what's the point of having an array then?
.@cornuz : for loop does not work here (you get back to the issue I described). you need to echo ${TAB[index]}; I found my way: I make an infinite loop, as soon as [ -n ${TAB[index]} ] is false, I break the loop. This way, I dont mind about how many lines the output contains. thanx again.
@achille for x in "${TAB[@]}"; do should iterate over the array's elements properly -- did you include the double-quotes? Skipping them will cause something like the original problem.
0

You were close:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.