如何将所有命令参数放在一个变量中 [英] how to put all command arguments in one variable

查看:111
本文介绍了如何将所有命令参数放在一个变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行一个需要3个参数的shell脚本.

I want to execute a shell script that require 3 arguments.

参数2包含一个带空格的字符串

The argument number 2 contains a string with space

我想将所有参数都放在一个这样的变量中:

I want to put all arguments in one variable like this:

Linux:~# kk="\"111\" \"222 222\" \"333\""
Linux:~# echo $kk
"111" "222 222" "333"

现在,如果我调用一个函数:

Now If I call a function:

func() {
  echo ---$1---
  echo ---$2---
  echo ---$3---
}

通过$ kk变量以这种方式

with the $kk variable in this way

func $kk

然后它将返回

Linux:~# func $kk
---"111"---
---"222---
---222"---

我期待得到这个结果

---111---
---222 222---
---333---

如何在不使用eval的情况下解决此问题?

How to solve this issue without using eval ?

我知道eval解决了这个问题,但是我不想使用它(因为如果我多次执行这样的调用会花费时间).

I know that the eval solve this issue but I do not want to use it (since it takes time if I execute many time a such call).

推荐答案

如果功能(如数组)没有使bash表现得比POSIX sh更具表现力,则没有理由添加它们. :)

If features (like arrays) didn't make bash more expressive than POSIX sh, there would have been no reason to add them. :)

也就是说,您可以通过根据需要覆盖"$@"来解决此问题:

That said, you can work around it by overriding "$@" for your needs:

set -- 111 "222 222" 333
printf '%s\n' "$@"

...将打印...

...will print...

111
222 222
333

如果您需要逐步构建参数列表,则可以使用"$@"作为第一个参数来多次调用set(确保您遵守引号!):

If you need to build the arguments list step by step, you can make several calls to set with "$@" as the first arguments (make sure you observe the quotes!):

set -- 111
set -- "$@" "222 222"
set -- "$@" 333
printf '%s\n' "$@"

...将打印...

...will print...

111
222 222
333

这篇关于如何将所有命令参数放在一个变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆