在我的脚本“script.sh”中,我想将第一个和第二个参数存储到某个变量,然后将其余参数存储到另一个单独的变量。我必须使用什么命令来执行此任务? 请注意,传递给脚本的参数数量会有所不同。
当我在控制台中运行命令时
./script.sh abc def ghi jkl mn o p qrs xxx #It can have any number of arguments
在这种情况下,我希望我的脚本将“abc”和“def”存储在一个变量中。 “ghi jkl mn o p qrs xxx”应该存储在另一个变量中。
最佳答案
如果您只想连接参数:
#!/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
关于bash - 将传递的参数存储在单独的变量中 -shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13869879/