0

How do I write a bash script/function that will take a command line argument with spaces and interpret it as if it had quotes around it.

ie: echo this is some text as if echo "this is some text"

What I want to do is create a simple CLI calculator script/function. Here is what I have:

calc() {
        echo $(($@))
}

On the CLI, all of these work:

"# +-/* ", #+-/*, # +-/ #

ie:

calc 10+2
12

but this one produces an error:

calc 10 * 2
-bash: 10 calc.sh 2: syntax error: invalid arithmetic operator (error token is ".sh 2")

Any ideas? It's not a big deal to include the quotes in the calculations, but if possible it would be quicker/more convenient to not include them. Is there any way to take a string after calc from first character to last and then pass it through quotes in the script?

ymonad
  • 10,300
  • 1
  • 31
  • 44
m147
  • 29
  • 4

1 Answers1

-1

In unix systems there is a variable called IFS. This variable decides at what signs the console separate the string into words. In theory you could chang the IFS variable, but this is really not advisable (as it will breake other bash commands).

Better: you could write your utillity in such way, that writing 'calc' will prompt the user to type his equation to standard in. Then you can read the text the user types and parse it in any way you want.

Even better: a shell script can specify that it wishes for an arbitrary nimber of words as input. Take all the words the user writes and then parse that. See: How to define a shell script with variable number of arguments?

user2887596
  • 675
  • 5
  • 13
  • Only the second suggestion will help. The shell parses the arguments (including expanding wildcards to lists of matching files) *before* passing them to the command (/function/script/whatever). By the time the command receives them, it's too late. – Gordon Davisson Jan 26 '18 at 08:42