2

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!!!

1
  • FYI assignments cannot have spaces around the =. You have to write MYOUTPUT="" not MYOUTPUT = "". Commented Nov 11, 2016 at 4:16

2 Answers 2

4

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]
Sign up to request clarification or add additional context in comments.

1 Comment

... isn't necessary. ... this is not exactly true. Assuming that you have a file /home/.myfile (which is unlikely, but possible), find /home would find it, but find /home/* would not.
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.