9

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.

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.

4

3 回答 3

13

如果您只想连接参数:

#!/bin/sh

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

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

#!/bin/sh

first_two="$1 $2"  # Store the first two arguments
a="$1"; b="$2"     # 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
于 2012-12-13T22:51:16.290 回答
4

切片$@数组。

var1=("${@:1:2}")
var2=("${@:3}")
于 2012-12-13T22:57:47.477 回答
2

将所有参数存储在表中

  vars=("$@")

  echo "${vars[10]}"
于 2016-04-11T20:23:50.253 回答