Tom
Tom

Reputation: 936

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" [email protected] $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" [email protected] $MYOUTPUT

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

Upvotes: 2

Views: 1372

Answers (2)

chw21
chw21

Reputation: 8140

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

Upvotes: 3

John Kugelman
John Kugelman

Reputation: 361585

mail will read from stdin. You can pipe the output of the loop to it without any temporary variables.

for user in *
do
    find /home/$user -type f -name "*myfile*" 
done | mail -s "the results" [email protected]

You could even get rid of the loop by having a single find command search all of the directories.

find /home/* -type f -name "*myfile*" | mail -s "the results" [email protected]

Actually, the * isn't necessary.

find /home -type f -name "*myfile*" | mail -s "the results" [email protected]

Upvotes: 4

Related Questions