0

I have been looking at other similar questions but didn't find the proper answer. $1 is the name of the array i want to loop over.

#!/bin/bash

for i in ${"$1"[@]}

do

echo "$i"

done
2
  • How do you call this script? Commented Jan 20, 2022 at 10:59
  • 2
    @n7rc : $1 is always a scalar. There is no way that you can invoke a script in a way that this parameter becomes an array. $@ would be (kind of) an array, but as a special variable, it does not act like an array in every respect. Commented Jan 20, 2022 at 12:33

2 Answers 2

1

If I don't misunderstand your not very well written question, you are looking for bash indirection, which is available since bash, version 2.

Below a minimal example

#! /bin/bash

foo=( 1 2 3 4 )
bar=( 5 6 7 8 )


if [[ ( "$1" -ne foo && "$1" -ne bar ) ]];
then 
    echo "Usage: $0 <foo|bar>"
    exit 1
fi

ambito="$1"[@]           # here what you are looking for

for i in "${!ambito}";   # here the indirection
do
    echo -n "$i "
done
echo ""

And you can call this indirection.sh scrit as:

$ ./indirection.sh  foo
1 2 3 4 

or

$ ./indirection.sh  bar
5 6 7 8 

This being said, using indirection may cause confusion. In most cases it could be replaced by associative arrays.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. That was the solution.
@n7rc You are welcome. I modified my answer, with a more detailed script and a link to documentation. Enjoy.
1

$1 is the first command line argument, not all of them. Probably what you are looking for is $@.

And to create an array holding them, something like:

ambito=($@)

4 Comments

No, it is precisely about passing the first argument of the command line that corresponds to one of the arrays contained in hosts.sh. Thanks for your reply.
well then the solution to your problem depends on what you mean by "corresponds".
if $1 holds the name of the array, you can write a switch statement
Thanks for your reply. I ask below what is my intention.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.