Tom Tom - 22 days ago 5
Bash Question

Combine output of for loop to variable

I have a question regarding the for loop in bash.

I want to write a script which is looping through the directory of each cpanel user and looks for a certain file. I only want to loop through the folders of cpanel users and not of other folders within the /home directory.

This is what i got so far:

cd /var/cpanel/users
for user in *
do
find /home/$user -type f -name "*myfile*"
done

mail -s "the results" my@email.com $MYOUTPUT


What i dont understand is, how I can collect all the output from the for..do..done loop and store it in one variable which i can send via email ($MYOUTPUT)

I was thinking doing it like this:

MYOUTPUT = ""
cd /var/cpanel/users

for user in *
do
WHAT=$(find /home/$user -type f -name "*myfile*")
$MYOUTPUT = $MYOUTPUT$WHAT
done


mail -s "result" my@email.com $MYOUTPUT


But that doesnt work.. Any ideas? Thank you!!!

Answer

First things first: To assign something to a variable, you have to

  1. Use the variable name without the $ before the = sign.
  2. not have any spaces surrounding the = character.

So what you'd need is something like this:

for i in {1..10}; do
    myvar="$myvar $i"
done
echo $myvar

Secondly, you can just redirect the whole output into a variable:

myvar=$(for i in {1..10}; do echo $i; done)
echo $myvar
Comments