Search code examples
bashparametersmailx

How can I build a dynamic parameter list for mailx command in bash linux?


OS: Red Hat Enterprise Linux Server release 5.11 (Tikanga)

I have a code sniplet:

!/usr/bin/env bash

v_mailx_parameter=""

v_cfg_email_adresse_to="john.doe_to@gmail.com"
v_cfg_email_subject="Report from December 2016"
v_tmp_email_text_name="Message Body"

v_email_main_file="appel orange.txt" # -> There is a SPACE in the file name! 
v_tmp_path="/home/server/tmp/"

if [ ! -z "${v_email_main_file}" ]
 then v_mailx_parameter="${v_mailx_parameter} -a \"${v_tmp_path}${v_email_main_file}\""
                                                 /\
                                                 ||
         Here is the problem but I need this because of spaces in the name
fi

echo -e "/bin/mailx ${v_mailx_parameter} -s \"${v_cfg_email_subject}\" \"${v_cfg_email_adresse_to}\""

cat ${v_tmp_email_text_name} | /bin/mailx ${v_mailx_parameter} -s "${v_cfg_email_subject}" "${v_cfg_email_adresse_to}"

exit

PROBLEM: I want to build up the parameters to the mailx command dynamically.

But I want to use the " double-quotes because there can be spaces in the file names.

Unfortunately the example above does not work... because the mailx takes the double-quotes as if they belong to the file name...and I get an error message.

I do not want to use the if else condition.. because I have many of files I need to send... I need a dynamic solution.

Maybe it is better to understand what my problem is:

It works in such a hardcoded way:

cat ${v_tmp_email_text_name} | /bin/mailx -a "/home/server/tmp/appel orange.txt" -s "${v_cfg_email_subject}" "${v_cfg_email_adresse_to}"

But so NOT:

v_mailx_parameter="-a \"${v_tmp_path}${v_email_main_file}\""

cat ${v_tmp_email_text_name} | /bin/mailx ${v_mailx_parameter} -s "${v_cfg_email_subject}" "${v_cfg_email_adresse_to}"

Thanks!


Solution

  • You need to use an array, which can hold all the arguments to easy logging and invocation. Note, though, that the input redirection to feed the message to mailx is not an argument.

    #!/usr/bin/env bash
    
    v_cfg_email_adresse_to="john.doe_to@gmail.com"
    v_cfg_email_subject="Report from December 2016"
    v_tmp_email_text_name="Message Body"
    
    v_email_main_file="appel orange.txt"
    v_tmp_path="/home/server/tmp/"
    
    if [ ! -z "${v_email_main_file}" ]; then
      v_mailx_parameters+=( -a "${v_tmp_path}${v_email_main_file}" )
    fi
    v_mail_x_parameters+=( -s "${v_cfg_email_subject}" )
    v_mail_x_parameters+=( "${v_cfg_email_adresse_to}" )
    
    printf '/binmailx %s < %s\n' "${v_mail_x_parameters[*]}" "${v_tmp_email_text_name}"
    /bin/mailx "${v_mailx_parameters[@]}" < "${v_tmp_email_text_name}"