Store Bash script arguments $@ in a variable

前端 未结 2 416
[愿得一人]
[愿得一人] 2021-01-01 05:52

How can I store $@ in a variable while keeping its properties?

I want to obtain exactly the same behavior even if I use $@ or my own varia

相关标签:
2条回答
  • 2021-01-01 06:21

    It depends what you want to do. Using $@ keeps the command-line arguments separated, if you want to join them together as a single string then use $* instead. For example:

    args="$*"
    java A $args
    

    When "$*" is used then the command-line arguments are joined into one string using the first character of IFS as the "glue" between each argument. By default that is a space. The only issue with this is if any of the arguments themselves contain whitespace. If you know that spaces are going to be used, not tabs, then you can mess with IFS:

    oldIFS="$IFS"
    IFS=$'\t'
    args="$*"
    java A.py $args
    
    IFS="$oldIFS"
    

    Edit: since you wish to keep them separate, then use an array:

    args=("$@")
    java A "${args[@]}"
    

    Using an "index" of @ has a similar effect to "$@" (you can also use * to join elements together, just like "$*").

    0 讨论(0)
  • 2021-01-01 06:25

    You can store it in an array:

    args=("$@")
    

    then you can access each of the arguments with index: "${args[index]}" and all arguments at once with "${args[@]}".

    0 讨论(0)
提交回复
热议问题