sobota, 21 listopada 2015

How to assign for loop output to a variable in bash

Just wrap the for loop inside the command substitution brackets $() or - regarded as deprecated - backticks `` and assign it to the variable, e.g.
kamil@kamil-elitebook:~$ cat test.sh 
#!/bin/bash
myvar=$(for i in {1..3}; do
echo $i
done)

echo "myvar=$myvar"


kamil@kamil-elitebook:~$ ./test.sh 
myvar=1
2
3