Jer
Jer

Reputation: 5648

How can I pass an unquoted string with spaces as a quoted argument?

Better explained with an example. I am writing a simple wrapper (a function in my .bashrc) around the mail command.

Here is my current function which doesn't work correctly:

function email_me() { echo "$@" | mail -s "\"$@\"" [email protected]; }

Here is my desired usage - this would send an email with both the subject and body set to testing 1 2 3. Note I specifically do not want to have to put quotes in manually.

~$ email_me testing 1 2 3

Thus I want the string replacement to occur like this:

echo "testing 1 2 3" | mail -s "testing 1 2 3" [email protected]

However no matter what I try, it's as though the -s argument doesn't have quotes around it, and email an email with the subject "testingis sent to the following recipients: 1, 2, 3, and [email protected]

How can I make the -s argument consider "testing 1 2 3" to be a single string?

Upvotes: 3

Views: 352

Answers (1)

Dmitry Grigoryev
Dmitry Grigoryev

Reputation: 3203

I would suggest using

function email_me() { printf %s\\n "$*" | mail -s "$*" [email protected]; }
  • "$*" is indeed the special variable containing all arguments together in one string
  • using printf instead of echo saves you from suprises with -n -e and whatever else your implementation of echo supports.

Still, there will be situations where you'll have to quote the arguments to email_me to avoid globbing and preserve whitespace:

email_me 2 * 2 = 4
[sends you all file names in current directory]
email_me a   b
[sends "a b" with only one space]

Upvotes: 3

Related Questions