Question

I'm trying to write a script that will take two numbers from the time of running the script. The script is called compute. I need it to take 2 inputs when I run the script, it would then output the result

Like this:

compute 3 + 1
3 + 1 = 4

any help is greatly appreciated!

Was it helpful?

Solution

You can access the arguments of a Bash script using $1, $2, $3, etc, where the number after the $ is the number of the argument. This means that if your script is called compute, then you could retrieve your "3 + 1" from ./compute 3 + 1 as the first three arguments using this syntax:

$1 would be 3, $2 would be +, and $3 would be 1.

The fastest way to implement what you want would be to simply piggyback on the Bash tool that already does this: expr. However, I'm assuming this is for a school assignment, so the objective is probably to roll your own; read up on math in Bash scripts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top