Store Bash script arguments $@ in a variable

試著忘記壹切 提交于 2019-11-29 15:43:31

问题


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 variable in all possible situations.

The attempts below didn't work:

args=$@
args2="$@"        # the arguments are combined (see the last output paragraph)

I tested them using the following line:

s.sh A B="       " C

s.sh

#!/bin/bash

args=$@
args2="$@"
#args3 = ? - TODO

echo $args
echo $args2
echo $@
#echo $args3   

echo

echo "$args"
echo "$args2"
echo "$@"
#echo "$args3"

echo

java A $args
java A $args2
java A $@
#java A $args3

echo

java A "$args"
java A "$args2"
java A "$@"
#java A "$args3"

A.java

import java.util.Arrays;

public class A {
    public static void main(String args[]){
        System.out.println(args.length + ": " + Arrays.asList(args));
    }
}

Actual output:

A B= C
A B= C
A B= C

A B= C
A B=        C
A B=        C

3: [A, B=, C]
3: [A, B=, C]
3: [A, B=, C]

1: [A B= C]
1: [A B=        C]
3: [A, B=       , C]

Expected output (if TODO is replaced by a solution) and echos are enabled

A B= C
A B= C
A B= C
A B= C

A B= C
A B=        C
A B=        C
A B=        C

3: [A, B=, C]
3: [A, B=, C]
3: [A, B=, C]
3: [A, B=, C]

1: [A B= C]
1: [A B=        C]
3: [A, B=       , C]
3: [A, B=       , C]

回答1:


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[@]}".




回答2:


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 "$*").



来源:https://stackoverflow.com/questions/30436869/store-bash-script-arguments-in-a-variable

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