bashshell

Appending output from a command to a variable in Bash


I'm trying to append an output of a command to a variable in Bash. My code is

#!/bin/bash

for file in *
do
    lineInfo=`wc -l $file`
    echo "$lineInfo"
done

I understand how to "capture" the output of a command to a variable as I have done in this line by the use of backquotes.

lineInfo=`wc -l $file`

Is there a clean cut way I can place the output of that entire for loop into a variable in Bash? Or in each iteration of the for loop append the output of the wc command to linesInfo ? (Without redirecting anything to files) Thanks.


Solution

  • This stores all the line infos (separated by commas) into one variable and prints that variable:

    #!/bin/bash
    
    total=""
    
    for file in *
    do
        lineInfo=`wc -l $file`
        total="$total$lineInfo, "  # or total+="$lineInfo, "
    done
    
    echo $total