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
-
2\$\begingroup\$ this will send a separate email for each file. Is that your intent? \$\endgroup\$glenn jackman– glenn jackman2013年07月16日 16:06:28 +00:00Commented Jul 16, 2013 at 16:06
1 Answer 1
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".
-
\$\begingroup\$ It's probably safe in this specific case but in general, people with a lot more experience than I don't recommend parsing the output of
ls
: mywiki.wooledge.org/ParsingLs For an even more in-depth discussion of the issue, see unix.stackexchange.com/questions/128985/why-not-parse-ls \$\endgroup\$Anthony Geoghegan– Anthony Geoghegan2016年03月04日 15:08:13 +00:00Commented Mar 4, 2016 at 15:08