简体   繁体   English

在bash中的命令之后立即读取多个参数

[英]read more than one parameters right after the command in bash

I am making a bash script and I want it to be just one line, meaning it will not have any interaction with the users and the parameters will be on the same line as the command. 我正在制作一个bash脚本,我希望它只是一行,这意味着它将与用户没有任何交互,并且参数将与命令位于同一行。 Once the user clicks return, it will output the result. 用户单击return后,将输出结果。 Right now, I have something that looks like this: 现在,我有这样的东西:

#! \bin\bash
read $1 $2
do something with $1 and $2

However, if I name my script "test" when I type in test at the beginning of the command line, I will have to type enter for the rest of the script to be executed. 但是,如果我在命令行开头键入test时将脚本命名为“ test”,则必须键入enter才能执行其余脚本。 How should I modify it so that I can run the entire thing on just one line? 我应该如何对其进行修改,以便我可以只在一行上运行整个程序?

The standard way to pass parameters to a script is not with read (which actively waits for input from stdin), but just to call your script with the parameters on the same line: 将参数传递到脚本的标准方法不是使用read (它会主动等待来自stdin的输入),而只是使用同一行中的参数来调用脚本:

./my_script.sh param1 param2

Then inside the script, you can access these parameters using $1 , $2 , etc. Example (note also the first line - this describes what shell should be used to run the script, and should be a valid path - ie /bin/bash , not backslashes): 然后,在脚本内部,您可以使用$1$2等访问这些参数。示例(请注意第一行-这描述了应使用哪种shell运行脚本,并且应是有效路径-即/bin/bash ,不反斜杠):

#!/bin/bash
echo "First: $1 Second: $2"

Then call the script: 然后调用脚本:

$ ./my_script.sh Hello There
First: Hello Second: There

What you probably need is this : 您可能需要的是:

You script name test.sh contains the following: 您的脚本名称test.sh包含以下内容:

 #!/bin/bash
 echo "$1 $2"

Then, change permission so that you can execute the script on the command line : 然后,更改权限,以便您可以在命令行上执行脚本:

chmod u+x test.sh

and run the script with arguments (two in this case) : 并使用参数运行脚本(本例中为两个):

./test.sh tik tak

will return 将返回

 tik tak

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM