how to put all command arguments in one variable

不羁岁月 提交于 2019-12-06 12:29:23

OP originally tagged question , then removed the tag. Please refer to Charles Duffy's great answer for a POSIX shell solution! the solution below uses arrays and is only suitable for .


You should not put your data in a string like this, but in an array. By the way, you're missing some quotes in your function:

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

or better yet (printf is preferable to echo):

func() {
    printf -- '---%s---\n' "$1"
    printf -- '---%s---\n' "$2"
    printf -- '---%s---\n' "$3"
}

$ kk=( "111" "222 222" "333" )
$ func "${kk[@]}"

will happily print:

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

You can even include newlines and such in your arguments:

$ kk=( $'one\none' "222 222" $' *   three\nthree' )
$ func "${kk[@]}"
---one
one---
---222 222---
--- *   three
three---
Charles Duffy

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

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!