How can I create a script that populates an array from user input in another script?

0
6
Asked By CuriousCoder101 On

I'm new to scripting and trying to figure out how to dynamically populate an array in my script based on user input, instead of hardcoding those values. Currently, I have this script that randomly types characters from a predefined array:

```bash
#! /bin/bash
arr[0]="0"
arr[1]="1"
arr[2]="2"
rand=$[$RANDOM % ${#arr[@]}]
xdotool type ${arr[$rand]}
```

What I want is a second script that prompts the user to enter a list of characters (like "r", "g", "q") and then uses that input to populate the array in the first script. I'm not sure how to handle this without editing the script manually every time I want to change the random characters. Any suggestions?

4 Answers

Answered By HelpSeeker92 On

Another approach is to read values from a file. Instead of creating a new script, just prompt the user for the values within your script. Here’s a quick way to do it:

```bash
#! /bin/bash
read -p "Enter a list of items separated by spaces: " -a arr

echo "${arr[@]}" > array_values.txt
```

Then modify your typing script to read from `array_values.txt`. This way, you don’t need multiple scripts!

Answered By RandomTechie77 On

You can also use the `$@` to pass command line arguments directly to the script. This allows you to populate an array without needing additional user prompts in a separate script.

Answered By ScriptingWhiz24 On

You could use a function to achieve this instead. It handles input better, especially if your values have spaces. Instead of hardcoding the array, create a function that receives the user input and populates the array dynamically.

Answered By ArrayExpert99 On

If you're worried about handling spaces in your input, you can use the following command to deal with it nicely:

```bash
#! /bin/bash
eval echo $$[$RANDOM % $#+1]
```

This lets you call your script with the array elements as arguments and select randomly from them.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.