How do I handle multiple quotes in an alias (for bash or zsh)

4

1

I am using zsh, and I am trying to use python as a simple calculator. I'm very familiar with python, but can't seem to get the alias (or function) to work properly.

So far I've got:

pycalc() {
  python -c "print '$@'"
}
alias p=pycalc

No matter what I do, it returns zsh: no matches found: 123*123 (123*123 being the math problem).

Any ideas???

AtHeartEngineer

Posted 2014-06-19T20:48:50.433

Reputation: 43

Answers

1

Bash
Add the following to .bashrc

pycalc() {
  python -c "print \"%f\" % float($@)"
}
alias p=pycalc

You can append it with the echo command.
One-line:

echo -e 'pycalc() {\n  python -c \"print \\\"%f\\\" % float($@)\"\n}\nalias p=pycalc' >> .bashrc

Multi-line:

echo -e 'pycalc() {
  python -c \"print \\\"%f\\\" % float($@)\"
}
alias p=pycalc' >> .bashrc

You can now use p

$ pycalc 12+12
24.000000
$ pycalc 12*12
144.000000
$ p 12+12
24.000000
$ p 12*12
144.000000

As Michael Righi noted in his answer, if you have file like 12*12, it will be matched by the 12*12 so you may want to enclose it in double quotes. You can also enclose it in single quotes. His solution works for bash too.

Bob

Posted 2014-06-19T20:48:50.433

Reputation: 40

I'm still getting zsh: no matches found: 2*2 when i enter p 2*2

I'm using zsh by the way, but I don't think that should make much of a difference. – AtHeartEngineer – 2014-06-19T23:04:09.050

Is pycalc 2*2 working? You added the modifications to .zshrc instead of .bashrc, right? – Bob – 2014-06-19T23:14:24.953

Did you reinitialize the terminal with the reset command so that the new .bashrc can be read? – Bob – 2014-06-19T23:46:30.493

2@BobJ reset has nothing to do with reloading ~/.bashrc. It is neither a prerequisite for it nor does it actively reload ~/.bashrc. If you want to load new settings from ~/.bashrc just call source ~/.bashrc. – Adaephon – 2014-06-20T05:46:17.943

Works!!!! yeah I did add it to zshrc instead of bashrc. i ran zsh again and it works!!!

Thanks! – AtHeartEngineer – 2014-06-20T12:32:50.360

4

zsh

Add this to .zshrc:

pycalc() {
  python -c "print $@"
}
alias p=pycalc

In your Z shell, use it like this:

$ p 12+12
24
$ p "12*12"
144

Notice you need the double quotes when the statement contains a globbing character such as the asterisk.

Or, you could turn off globbing for that alias:

pycalc() {
  python -c "print $@"
}
alias p='noglob pycalc'

That eliminates the need for the double quotes when you use it:

$ p 12+12
24
$ p 12*12
144

Michael Righi

Posted 2014-06-19T20:48:50.433

Reputation: 141