0

can you please tell me why this is not working? only the add 'e f' after the read loop is done, but not the multiple adds 'q w' inside the read loop. regards stefan

vuser1@vpc1:~$ echo ${#a[@]}
1
vuser1@vpc1:~$ ls
Desktop  Documents  Downloads  Music  Pictures  Public  Templates  Videos
vuser1@vpc1:~$ set -x
vuser1@vpc1:~$ a=();ls -l|while read x; do a+=("q w");done;a+=("e f")
+ a=()
+ ls --color=auto -l
+ read x
+ a+=("q w")
+ read x
+ a+=("q w")
+ read x
+ a+=("q w")
+ read x
+ a+=("q w")
+ read x
+ a+=("q w")
+ read x
+ a+=("q w")
+ read x
+ a+=("q w")
+ read x
+ a+=("q w")
+ read x
+ a+=("q w")
+ read x
+ a+=("e f")
vuser1@vpc1:~$ echo ${#a[@]}
+ echo 1
1
vuser1@vpc1:~$ echo ${a[@]}
+ echo e f
e f
vuser1@vpc1:~$```

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Btw.: Please note: [Why *not* parse `ls`?](http://unix.stackexchange.com/questions/128985/why-not-parse-ls) – Cyrus Jun 13 '21 at 06:17
  • 1
    When executing a pipeline, you execute it in a subshell. This means that variable assignments are only known to that subshell. After the pipeline, the assignments are unknown to the original shell. Use redirection instead: `while IFS= read -r line; do a+=( "$line" ); done < <(command)` – kvantour Jun 13 '21 at 06:27
  • 1
    `a=();while read x; do a+=( "q w" );done < <(ls -l);a+=( "e f" ); echo "${a[@]}"` – Akshay Hegde Jun 13 '21 at 06:29
  • hi, thank you all for the help. i would never have come to the reason with subshell. here i found now another solution in google with herestring ```a=();while read x; do a+=("$x");done <<< "$(ls)";echo ${#a[@]}``` or just ```a=(`ls`)``` – stefan-eibl Jun 13 '21 at 07:13
  • here i found another working solution for storing whitespaced command outputs into array:```pi@raspi:~ $ a=();while read x; do a+=("$x");done <<< "$(grep -inrE '/usr/lib/cgi-bin' /etc/apache2/)";echo ${#a[@]};echo ${a[1]}``` the good thing in this is, that no need to edit and restore this IFS thing. – stefan-eibl Jun 14 '21 at 05:13

0 Answers0