加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 22:47:19 所属栏目:安全 来源:网络整理
导读:在我的脚本“script.sh”中,我想将第一个和第二个参数存储到某个变量中,然后将其余参数存储到另一个单独的变量中.我必须使用什么命令来执行此任务? 请注意,传递给脚本的参数数量会有所不同. 当我在控制台中运行命令时 ./script.sh abc def ghi jkl mn o p q
在我的脚本“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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读