根据参数数量循环创建数组 [英] Create array in loop from number of arguments

查看:91
本文介绍了根据参数数量循环创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/bin/bash
COUNTER=$#
until [ $COUNTER -eq 0 ]; do
args[$COUNTER]=\$$COUNTER
let COUNTER-=1
done
echo ${args[@]}

运行此命令时,我得到以下结果

When i run this, I get the following results

user@host:~/sandbox# ./script.sh first second third
$1 $2 $3

我希望它能回显$ 1,$ 2和$ 3不是文本值"$ 1"

and i'm expecting it to echo out what $1, $2, and $3 are not a text value of "$1"

我试图用bash编写一个脚本,该脚本将创建一个数组,该数组的大小与我提供的参数数量相同.
我期待着

I'm trying to write a script in bash that will create an array that is the size of the number of arguments I give it.
I'm expecting

user@host:~/sandbox# ./script.sh alpha bravo charlie
alpha bravo charlie

user@host:~/sandbox# ./script.sh 23425 jasson orange green verb noun coffee
23425 jasson orange green verb noun coffee

所以,目标是制造

args[0]=$1
args[1]=$2
args[2]=$3
args[3]=$4

我拥有它的方式$1,$2,$3不会被插值,而只是作为文本字符串读取.

The way that I have it, the $1,$2,$3 aren't being interpolated but just being read as a text string.

推荐答案

您可以使用+=运算符将其追加到数组.

You can use the += operator to append to an array.

args=()
for i in "$@"; do
    args+=("$i")
done
echo "${args[@]}"

这显示了如何完成附加操作,但是获得所需结果的最简单方法是:

This shows how appending can be done, but the easiest way to get your desired results is:

echo "$@"

args=("$@")
echo "${args[@]}"

如果要保留现有方法,则需要使用

If you want to keep your existing method, you need to use indirection with !:

args=()
for ((i=1; i<=$#; i++)); do
   args[i]=${!i}
done

echo "${args[@]}"

来自Bash参考:

如果参数的第一个字符是感叹号(!),则 引入了变量间接级别. Bash使用以下值 由其余参数组成的变量作为 多变的;然后扩展此变量,并在 其余的替换,而不是参数本身的值. 这称为间接扩展.例外情况是 $ {!prefix}和$ {!name [@]}的扩展如下所述.这 感叹号必须紧跟左括号,以便 引入间接.

If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of ${!prefix } and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

这篇关于根据参数数量循环创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆