Bash script - Truncating Variable

The place to post if you need help or advice

Moderators: ChriThor, LXF moderators

Bash script - Truncating Variable

Postby Arthur_Dent » Thu Sep 20, 2012 6:46 pm

Hello all,

I don't speak fluent bash. I can just about order a beer in a bar, but I am a long way off being able to chat with a local.

I use a script called clamassassin to pipe emails through clamd. It marks up the email headers (using formail) with the results of the scan. The problem is that the script has not been developed since 2007 and the author cannot be contacted. There is a fault with the script and I am trying to fix it myself but my bash scripting skills are letting me down.

The script first obtains the clamd version but calling "clamdscan -V" and reading it into a variable called $CLAMVERS. If there is a problem with clamd (daemon not running - file permission... whatever...) it returns something like:
Code: Select all
ERROR: Can't connect to clamd: Permission denied
ClamAV 0.97.5

Note that there is a line-break in there. When the script goes on to put this into the headers using formail the line-break corrupts the email.

I am trying to fix this, but still retain the error detail, by cutting off the line break and the ClamAV... part.

This is where I need help...

Code: Select all
# Set version header string
CLAMVERS=`${CLAMSCAN} -V --stdout`

if [[ "$CLAMVERS" == *ERROR* ]] # Not how it works in the script, but OK for testing
   ERRORMSG=`echo ${CLAMVERS} | sed -e "/ClamAV/!d" -e "s/.* //"`
   echo "Error = :${ERRORMSG}"

   echo "ClamVersion = $CLAMVERS"

Essentially I want to cut off anything after the ClamAV part and the character before that (the line break).

I'm stuck.

Any fluent bash speakers care to help me?

Thanks in advance.

LXF regular
Posts: 219
Joined: Mon Jan 02, 2006 11:05 am
Location: London

Postby Arthur_Dent » Sat Sep 22, 2012 6:16 am

Replying to my own post:

I have found a solution to this. I'm sure there are better ways, but this works.

Code: Select all
# Define the newline character to be found and stripped out:
# I tried variations of "\n" but that didn't seem to work.

The %{string}* thing means strip out everything after and including {string}. There is an equivalent directive #*{string} which means strip out everything up to and including {string}. I had never come across the % and # directives in string handling before. It does what I want anyway...
LXF regular
Posts: 219
Joined: Mon Jan 02, 2006 11:05 am
Location: London

Postby MartyBartfast » Sat Sep 22, 2012 6:48 am

good find, could come in very handy, I've used awk for such things but always thought it was a bit cluncky.
I have been touched by his noodly appendage.
LXF regular
Posts: 842
Joined: Mon Aug 22, 2005 7:25 am
Location: Hants, UK

Return to Help!

Who is online

Users browsing this forum: Bing [Bot] and 1 guest