Angel.King.47 Angel.King.47 - 1 month ago 6
Bash Question

Return two variables in awk

At the moment here is what im doing

ret=$(ls -la | awk '{print $3 " " $9}')
usr=$(echo $ret | awk '{print $1}')
fil=$(echo $ret | awk '{print $2}')


The problem is that im not running an
ls
im running a command that takes time, so you can understand the logic.

Is there a way I can set the return value to set two external values, so something such as

ls -la | awk -r usr=x -r fil=y '{x=$3; y=$9}'


This way the command will be run once and i can minimize it to one line

Answer

A workaround using read

usr=""
fil=""
while read u f; do usr="$usr\n$u"; fil="$fil\n$f"; done < <(ls -la | awk '{print $3 " "  $9}')

For performance issue you could use <<<, but avoid it if the returned text is large:

while read u f; do usr="$usr\n$u"; fil="$fil\n$f"; done <<< $(ls -la | awk '{print $3 " "  $9}')

A more portable way inspired from @WilliamPursell's answer:

$ usr=""
$ fil=""
$ while read u f; do usr="$usr\n$u"; fil="$fil\n$f"; done << EOF
> $(ls -la | awk '{print $3 " "  $9}')
> EOF