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
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!
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.
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.
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
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically
[Centos] Delete All Files And Folders That Contain a String