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

April 21, 2025 4 answers
Asked by CuriousCoder101
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?

Answers

ArrayExpert99
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.
Reply to this answer
ScriptingWhiz24
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.
Reply to this answer
RandomTechie77
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.
Reply to this answer
HelpSeeker92
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!
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions