Create array in loop from number of arguments

不问归期 提交于 2019-11-29 05:44:14

问题


#!/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

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

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

or

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

So, the goal is to make

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

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


回答1:


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 "$@"

or

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

From the Bash reference:

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.



来源:https://stackoverflow.com/questions/15420790/create-array-in-loop-from-number-of-arguments

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