0

Is it possible when I want to assign values to the correct index in array (array in bash)? when I enter some number I want that this number was on the same position as its value..

example: when I enter number 25 and then use command echo ${array[25]} I expect 25

I want to give numbers from shuf -i 1-49 -n 7 | xargs -n7 to array. Every number on his position.

Thanks for answers :)

2
  • You want to create a sparse array of seven random values each assigned to its index value? Commented Dec 26, 2014 at 16:02
  • Can you explain why you'd want this? If I enter 25, why pull up ${a[25]} just to get the value of 25? It's certainly not very efficient. Imagine if I define array foo, then said foo[1000]='bar'. I'd be taking up 1001 memory locations. There might be a better way to do what you want. Commented Dec 26, 2014 at 18:02

1 Answer 1

1

You could just loop over the result of shuf:

#!/bin/bash
while read i
do
  a[$i]=$i
done < <( shuf -i 1-49 -n 7 )

for i in "${!a[@]}"; do
  printf "%s\t%s\n" "$i" "${a[$i]}"
done
Sign up to request clarification or add additional context in comments.

Comments

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.