Thatbytes

Mostly Interesting

Reading Stdin Bash Style

Have you ever had the need to read standard input in a bash script, for example

1
cat /var/log/message | mycoolbashscript.sh

Well i did when wrapping msmtp for use with mutt see the example bellow

1
2
3
4
5
6
7
8
9
#!/bin/bash
all=`cat "/dev/stdin"`

if `/sbin/ifconfig eth0 | /bin/grep "inet addr" | /usr/bin/awk -F: '{ print $2 }'' | /usr/bin/awk '{ print $1 }'' |  /bin/grep -qE '172\.31|32\.[0-9]{1,3}\.[0-9]{1,3}'`; then
echo "$all" | tsocks msmtp -a account $*
else
echo "$all" | msmtp -a account $*
fi

I then setup mutt to use this as the sendmail binary

1
set sendmail="~/utils/sendmail.sh"

This basically reads, if im in the network 172.31 or 172.32 then run msmtp through tsocks if not then just run msmtp, this allowed me to use tsocks to proxyfy msmtp under certain circumstances. But i could also do other things like read the from header and switch the account msmtp uses to send the mail. It passes all standard input to the msmtp binary as well as all the command arguments passed to my sendmail.sh.

Although im sure other people can create more interesting uses.

Comments