Search code examples
bashcommand-lineemail-attachmentsmutt

find file then select for mutt attachment


I am looking to streamline sending attachments with a fixed body message using the following bash script,

#!/bin/sh
echo "body of message" | mutt -s "subject" -a $(find /path/to/dir -type f -name "*$1*") -- $2 < /dev/null

however, sometimes the find command finds multiple files for attachment. Is there a more interactive way of doing this? For instance, if it finds files xyz.pdf, and xyz2.pdf that I can select one and then proceed with sending the file?


Solution

  • You can pass the output of find to the select command. It's a loop that lets you repeatedly select an item from a list of choices and run the body of the loop using the just selected value.

    select attachment in $(find /path/to/dir -type f -name "*$1*"); do
        echo "body of message" | mutt -s "subject" -a "$attachment" -- "$2" < /dev/null
        break   # To avoid prompting for another file to send
    done
    

    It's not ideal; it will break if it finds any files with whitespace in their names. You can be a little more careful about how you build the list of files (which is beyond the scope of this answer), then call the select command. For example:

    # Two poorly named files and one terribly named file
    possible=("file 1.txt" "file 2.txt" $'file\n3.txt')
    
    select attachment in "${possible[@]}"; do
        echo "body of message" | ...
        break
    done