将Bash脚本参数$ @存储在变量中 [英] Store Bash script arguments $@ in a variable
本文介绍了将Bash脚本参数$ @存储在变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在保持其属性的同时将$@
存储在变量中?
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.
以下尝试无效:
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));
}
}
实际输出:
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]
预期输出(如果将TODO替换为解决方案)并且启用了echo
Expected output (if TODO is replaced by a solution) and echo
s 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]
推荐答案
您可以将其存储在数组中:
You can store it in an array:
args=("$@")
然后您可以使用索引"${args[index]}"
访问每个参数,并使用"${args[@]}"
一次访问所有参数.
then you can access each of the arguments with index: "${args[index]}"
and all arguments at once with "${args[@]}"
.
这篇关于将Bash脚本参数$ @存储在变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文