linux bash使用脚本开头的输入编写脚本

时间:2022-01-22 05:45:26

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

我正在尝试编写一个脚本,从运行脚本开始将占用两个数字。该脚本称为compute。我运行脚本时需要它输入2个输入,然后输出结果

Like this:

compute 3 + 1
3 + 1 = 4

any help is greatly appreciated!

任何帮助是极大的赞赏!

1 个解决方案

#1


1  

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,$ 2,$ 3等访问Bash脚本的参数,其中$后面的数字是参数的编号。这意味着如果您的脚本被称为compute,那么您可以使用以下语法从./compute 3 + 1中检索“3 + 1”作为前三个参数:

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

1美元将是3美元,2美元将是+,3美元将是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.

实现你想要的最快的方法就是简单地搭载已经执行此操作的Bash工具:expr。但是,我假设这是一个学校作业,所以目标可能是你自己的;阅读Bash脚本中的数学。

#1


1  

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,$ 2,$ 3等访问Bash脚本的参数,其中$后面的数字是参数的编号。这意味着如果您的脚本被称为compute,那么您可以使用以下语法从./compute 3 + 1中检索“3 + 1”作为前三个参数:

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

1美元将是3美元,2美元将是+,3美元将是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.

实现你想要的最快的方法就是简单地搭载已经执行此操作的Bash工具:expr。但是,我假设这是一个学校作业,所以目标可能是你自己的;阅读Bash脚本中的数学。