bash 将传递的参数存储在单独的变量中 -shell 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13869879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:01:27  来源:igfitidea点击:

storing passed arguments in separate variables -shell scripting

bashshellargument-passing

提问by Nathan Pk

In my script "script.sh" , I want to store 1st and 2nd argument to some variable and then store the rest to another separate variable. What command I must use to implement this task? Note that the number of arguments that is passed to a script will vary.

在我的脚本 "script.sh" 中,我想将第一个和第二个参数存储到某个变量,然后将其余的存储到另一个单独的变量。我必须使用什么命令来执行此任务?请注意,传递给脚本的参数数量会有所不同。

When I run the command in console

当我在控制台中运行命令时

./script.sh abc def ghi jkl mn o p qrs xxx   #It can have any number of arguments

In this case, I want my script to store "abc" and "def" in one variable. "ghi jkl mn o p qrs xxx" should be stored in another variable.

在这种情况下,我希望我的脚本将“abc”和“def”存储在一个变量中。“ghi jkl mn op qrs xxx”应该存储在另一个变量中。

回答by William Pursell

If you just want to concatenate the arguments:

如果您只想连接参数:

#!/bin/sh

first_two=" "  # Store the first two arguments
shift              # Discard the first argument
shift              # Discard the 2nd argument
remainder="$*"     # Store the remaining arguments

Note that this destroys the original positional arguments, and they cannot be reliably reconstructed. A little more work is required if that is desired:

请注意,这会破坏原始位置参数,并且无法可靠地重建它们。如果需要,还需要做更多的工作:

#!/bin/sh

first_two=" "  # Store the first two arguments
a=""; b=""     # Store the first two argument separately
shift              # Discard the first argument
shift              # Discard the 2nd argument
remainder="$*"     # Store the remaining arguments
set "$a" "$b" "$@" # Restore the positional arguments

回答by Ignacio Vazquez-Abrams

Slice the $@array.

切片$@数组。

var1=("${@:1:2}")
var2=("${@:3}")

回答by Iluvatar

Store all args in table

将所有参数存储在表中

  vars=("$@")

  echo "${vars[10]}"