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" Someone@somewhere.com
  fi
done
\$\endgroup\$
  • 2
    \$\begingroup\$ this will send a separate email for each file. Is that your intent? \$\endgroup\$ – glenn jackman Jul 16 '13 at 16:06
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".

\$\endgroup\$

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.