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

Nat*_* Pk 6 bash shell argument-passing

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

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

./script.sh abc def ghi jkl mn o p qrs xxx   #It can have any number of arguments
Run Code Online (Sandbox Code Playgroud)

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

Wil*_*ell 10

如果你只想连接参数:

#!/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
Run Code Online (Sandbox Code Playgroud)

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

#!/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
Run Code Online (Sandbox Code Playgroud)