I'm trying to write a simple script:

stat=$(du /home/test/)
for i in "$stat"; do
folder=$("$i" | awk '{print $2}')
mail -s $folder kenny@gmail.com

I run the script in shell and the output looks like:

4       /home/test/.config/mc/mcedit
12      /home/test/.config/mc
16      /home/test/.config

I then insert echo in the script before the loop, and the output then looks like:

4 /home/test/.config/mc/mcedit 12 /home/test/.config/mc 16 /home/test/.config

This is because without double-quotes. With double-quotes output is the same as in shell. So then using double-quotes for variables in loop cycle variable $folder don't work as expected. Instead it contains all values from list.

How to resolve this?

  • mail command lack proper entry, are you sure this is what you expect ? why don't you pipe du into awk and for loop directly ? – Archemar Apr 22 '17 at 13:32
  • "I" is always uppercase in English. – peterh Apr 22 '17 at 15:28

Here is a way to achieve what you look for, although not using a for loop but a while one:

stat=$(du /home/test/)
echo "$stat" | while read i; do
    folder=$(echo "$i" | awk '{print $2}')
    echo "mail content" | mail -s $folder kenny@gmail.com

Of course, as Archemar already commented, there is no reason not to directly pipe du output to the loop:

du /home/test/ | while read i; do
    folder=$(echo "$i" | awk '{print $2}')
    echo "mail content" | mail -s $folder kenny@gmail.com

Awk isn't really necessary either. The script can be simplified that way:

du /home/test/ | while read size folder; do
    echo "mail content" | mail -s "$folder" kenny@gmail.com

As you doesn't seem to make use of the directories sizes, which is what du is designed to compute, you might use find instead:

find /home/test -type d | while read folder; do
    echo "mail content" | mail -s "$folder" kenny@gmail.com
  • I wanna insert a path as subject in mail. in my case with double-quotes in subject looks /home/test/.config/mc/mcedit /home/test/.config/mc /home/test/.config But i want send 3 mails with different subject ex.: 1 mail with subject /home/test/.config/mc/mcedit 2 mail with subject /home/test/.config/mc 3 mail with subject /home/test/.config – DeadKenny Apr 22 '17 at 13:48
  • Sure, but what do you expect to put in the mail body? – jlliagre Apr 22 '17 at 13:53
  • Did you try my script? – jlliagre Apr 22 '17 at 13:53
  • Mail body contain random text. Yep, your version work fine. Tnx. I was thought i can use "for" loop cycle. – DeadKenny Apr 22 '17 at 13:58
  • The while loop is also supremely unnecessary. You are looking simply for du /home/^test/ | awk '{ print $2}' – tripleee Apr 22 '17 at 18:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.