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

标签 bash shell argument-passing

在我的脚本“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/

相关文章:

linux - 将日志条目安排到标有日期的文件中

bash - `xdotool type ` - 随机重复字符

linux - 在 while 循环之外时,无法读取从 while 循环中存储的变量

c# - 我如何通过 C# 中的函数动态获取属性?

eval - Tcl:如何评估语句以在调用时填写默认参数

linux - 从 grep 输出中删除 </p> 标签

git - 如何从 bash 脚本中监听 webhooks?

c++ - 为什么在这里使用进程替换会导致挂起?

mongodb - 在 Mongo Shell 中加密文档字段

c - 如何将字符串传递给这个 MD5 程序?