I’m new to bash shell scripting and it is my first day and first time to post a question here in stackoverflow. I already searched the archive to no avail. I hope someone can help me.
I have an array like this
declare -a SID=("mydb1" "mydb2" "mydb3")
In my script, the user will be prompted to enter a string and it will be stored in $DBNAME variable.
For example a user entered “mydb2” (without quote), this will be stored in $DBNAME variable.
I want to create a loop and I want the input of the user to be tested against each element of the ${SID[@]} variable.
And when a match found, it will exit from the loop and continue with the next command in a script.
Please help me create a script to match a string value against each element of an array variable.
Any help would be highly appreciated. Thank you!
If all you want to do is check that the user entered a valid dbname, do this:
This can lead to false-positives in cases where you allow space-containing user-input. If this is a concern, you can solve the problem by using a non-space delimiter that is not allowed in the user’s input. For example:
If your user input is completely open-ended, and unvalidated, then a for loop is probably your best bet, as explained in @glennjackson’s answer.