I have a variable which contains multiline output of a command. What's the most effecient way to read the output line by line from the variable?
For example:
jobs="$(jobs)"
if [ "$jobs" ]; then
# read lines from $jobs
fi
|
|
|
You can use a while loop with process substitution:
To read a multiline variable, a simple way is:
Also, please don't call your variable |
|||||||||
|
|
To process the output of a command line by line (explanation):
If you have the data in a variable already:
Note that in some shells (ash, bash, pdksh, but not ksh or zsh), the right-hand side of a pipeline runs in a separate process, so any variable you set in the loop is lost. For example, the following line-counting script prints 0 in these shells:
A workaround is to put the remainder of the script (or at least the part that needs the value of
If acting on the non-empty lines is good enough and the input is not huge, you can use word splitting:
Explanation: setting |
||||
|
|
|
In recent bash versions, use
Disclaimer: horrible example, but you can prolly come up with a better command to use than ls yourself |
|||
References: |
|||||
|
|
Problem: if you use while loop it will run in subshell and all variables will be lost. Solution: use for loop
|
|||
|
|
|
I would go with:
(if the output from |
|||||||||
|