Bobby
Bobby

Reputation: 43

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.

Upvotes: 3

Views: 13972

Answers (3)

little_birdie
little_birdie

Reputation: 5857

Use a subshell around the loop and then assign the stdout of the subshell to a variable. You can execute multiple commands within the parenthesis, anything sent to stdout will end up in captured.

captured=$(
    for file in *`enter code here`
    do
        wc -l $file
    done
)

echo "Here is the captured output:"
echo "$captured"

Upvotes: 0

tripleee
tripleee

Reputation: 189387

You can put the entire loop in the command substitution:

linesinfo=$(for file in *; do
        wc -l $file; done)

But of course, wc lets you run it on multiple files:

linesinfo=$(wc -l *)

While the output is reasonably machine-readable, a better approach in modern Bash would perhaps be to assign each result to a new element in an associative array.

declare -A linesinfo

for file in *; do
    linesinfo["$file"]=$(wc -l <"$file")
done

Somewhat surprisingly, use "${!linesinfo[@]}" to loop over the keys.

for file in "${!linesinfo[@]}"; do
    echo "'$file' size ${linesinfo[$file] bytes"
done

Demo: https://ideone.com/FMGUyM

Associative arrays are not available in Bash v3 so this will not work out of the box on MacOS, which still ships a really old version of Bash.

Notice how running wc with a redirection produces just the actual number of lines (whereas wc -l "$file" would produce something like 42 filename.txt with leading spaces).

Upvotes: 0

geckon
geckon

Reputation: 8754

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

Upvotes: 3

Related Questions