Convert command line arguments into an array in Bash

后端 未结 7 1379
清歌不尽
清歌不尽 2020-11-27 11:10

How do I convert command-line arguments into a bash script array?

I want to take this:

./something.sh arg1 arg2 arg3

and convert it

7条回答
  •  忘掉有多难
    2020-11-27 11:47

    Actually your command line arguments are practically like an array already. At least, you can treat the $@ variable much like an array. That said, you can convert it into an actual array like this:

    myArray=( "$@" )
    

    If you just want to type some arguments and feed them into the $@ value, use set:

    $ set -- apple banana "kiwi fruit"
    $ echo "$#"
    3
    $ echo "$@"
    apple banana kiwi fruit
    

    Understanding how to use the argument structure is particularly useful in POSIX sh, which has nothing else like an array.

提交回复
热议问题