Linux: Hassle with “mail”-command

I just had a little annoying trouble with “mail”. Despite it’s silly reason I will post it here to keep others from having to spend unnecessarily time on it.

I wanted to mail a logfile via “mail” from my Linux-Box. Easy, one might think. ;o)
But I got stuck with this error:

WARNING: RunAsUser for MSP ignored, check group ids (egid=3270, want=51)
can not chdir(/var/spool/clientmqueue/): Permission denied
Program mode requires special privileges, e.g., root or TrustedUser.

I used this line in my script:

echo "Monitor-Log `date`" | /bin/mail -s "Monitor-Log" -a /some/dir/monitor.log $RECIPIENTS -c $CCRECIPIENTS

The reason for the error was the sequence of the variables holding the mail-recipients (“$RECIPIENTS” and “$CCRECIPIENTS”). The last parameter to “mail” must ever be the final recipient. So all “CC”s have to go before that. The correct line is this:

echo "Monitor-Log `date`" | /bin/mail -s "Monitor-Log" -a /some/dir/monitor.log -c $CCRECIPIENTS $RECIPIENTS

As the given error-message is not straight for the root, I think this post was worth written.


bash-scripting: preserve whitespaces in variables

When you want to store a string like

"abc        def    gh ijk"

in a variable on a linux-shell, you’d be normally faced with this:

bash> VAR1="abc        def    gh ijk"
bash> echo $VAR1
abc def gh ijk

Your whitespaces are trimmed. This is a problem if you need the exact string e.g. for a string-compare.
The cause of this behaviour is the internal shell variable $IFS (Internal Field Separator), that defaults to whitespace, tab and newline.
Thus the variable $VAR1, when passed over to “echo”, is not seen as one single string but as a bunch of strings separated by whitespaces:

bash> VAR1="abc        def    gh ijk"
bash> for a in $VAR1
> do
> echo $a
> done

To preserve all contiguous whitespaces you have to set the IFS to something different:

bash> IFS='%'
bash> echo $VAR1
abc        def    gh ijk
bash> for a in $VAR1; do echo $a; done
abc        def    gh ijk

Afterwards you can switch back to default with “unset IFS”:

bash>unset IFS
bash>echo $VAR1
abc def gh ijk

Edit 2014-05-21:
Please read Martin’s advice and my reply on it below for another approach.