My digital playground

Creating a “bash alias” with an argument

Filed under: Uncategorized — Andre @ 14:41 September 16th, 2009

While setting up and testing the anti virus/spam filter of a mail server I usually send a lot of “test spam” to myself and that involves a pretty long line that needs to be typed in every time, and changed for every mail account i test. I want to make an alias for this using an argument containing the email address, but bash makes it hard if not impossible to do so with an alias. Fortunately it allows you to create an function instead.

The command for sending a “GTUBE” test spam message is

sendmail john@example.com < /usr/share/doc/spamassassin/examples/sample-spam.txt

To make this easier I wanted to make an alias for it, so I can type sendspam <email -address> to send it. And as I mentioned earlier bash don’t allow you to use arguments in aliases. But making a function is just as easy. Add the following line in ~/.bashrc

sendspam () { sendmail "$1"  < /usr/share/doc/spamassassin/examples/sample-spam.txt; }

After the next login you will now be able to use the following command to send a test spam message

sendspam john@example.com

4 Comments »

  • hi there,

    you dont need to re-log to get the results immidiately, just type “source .bashrc”

    (I assume that you are in the same dir with .bashrc else you need to type the full path to the edited .bashrc file)

    take care.

    Comment by fatih — January 14th, 2010 @ 23:06

  • In this specific case you wouldn’t have needed to use a function. Alias pass the arguments, and this can be rewritten as:
    cat /doc/spamassassin/examples/sample-spam.txt |sendmail john@example.com

    So your alias would be
    alias sendspam=’cat /doc/spamassassin/examples/sample-spam.txt | sendmail’

    Comment by Ángel — July 22nd, 2011 @ 11:06

  • I recently found a way to pass arguments to bash alias, without using functions. Took me a while to work it out though:

    alias foo=”xargs -I {} bash -c ‘/bin/find {}’ <<<"

    returns
    ./a.eps
    ./b.eps

    Comment by Christophe — August 26th, 2011 @ 16:44

  • Your article really helped me thanks, I wait for the next

    Comment by romi — December 16th, 2011 @ 22:00

RSS feed for comments on this post. TrackBack URL

Leave a comment