4
\$\begingroup\$

I want to list the contents of a folder and mail the list using a shell script. I Came up with the following script, please let me know if it is okay:

for file in *
do
 if [ -f "$file" ]; then
 echo "$file" | mail -s "List of files" [email protected]
 fi
done
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jul 16, 2013 at 14:24
\$\endgroup\$
1
  • 2
    \$\begingroup\$ this will send a separate email for each file. Is that your intent? \$\endgroup\$ Commented Jul 16, 2013 at 16:06

1 Answer 1

2
\$\begingroup\$

As @Juaniyyoo already mentioned, ls is the usual way to list all the files in a directory. I'm not sure if you really want to send a separate email for each file. If you do, you can iterate over each file with a while loop.

ls | while read file; do mail ... <<< "$file"; done

If what you really intended was to send the whole list in one go, this is even simpler.

ls | mail ...

ls has a lot of options for controlling the output format. With no options, it will just write the name of each file. ls -l lists permissions, number of links, owner user, owner group, size, modification date and name. The date modified might be interesting, i.e. when it was received, but the other one are probably not.

ls -l | sed -E 's/([^ ]+ +){5}//' | mail ...

Use this command to filter out the first 5 columns, and thus only get the date and filename columns. You might also want to sort the output - for this use the option --sort=time.

The first output line from ls -l is a header saying something like total 8440. You can skip this first line with tail -n+2.

ls -l | tail -n+2 | sed -E 's/([^ ]+ +){5}//' | mail ...

If you want the date and time in another format, use the --time-style option for ls.

Using ls instead of your rolling with your own loop provides a lot of utility, and prevents you from "reinventing the wheel".

answered Jul 14, 2015 at 10:28
\$\endgroup\$
1

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.