针对数组的每个元素测试字符串
我是 bash shell 脚本编写的新手,这是我第一天也是第一次在 stackoverflow 上发布问题。我已经搜索过档案没有结果。我希望有人能帮助我。
我有一个像这样的数组
declare -a SID=("mydb1" "mydb2" "mydb3")
在我的脚本中,系统将提示用户输入一个字符串,并将其存储在 $DBNAME 变量中。
例如,用户输入“mydb2”(不带引号),这将存储在 $DBNAME
变量中。
我想创建一个循环,并且希望针对 ${SID[@]
} 变量的每个元素测试用户的输入。
当找到匹配项时,它将退出循环并继续执行脚本中的下一个命令。
请帮助我创建一个脚本来将字符串值与数组变量的每个元素进行匹配。
任何帮助将不胜感激。谢谢你!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
@Flimzy 的方法很好。使用for循环的正确方法是
@Flimzy's approach is good. The correct way to use a for-loop is
如果您只想检查用户是否输入了有效的数据库名,请执行以下操作:
如果您允许包含空格的用户输入,这可能会导致误报。如果这是一个问题,您可以通过使用用户输入中不允许的非空格分隔符来解决问题。例如:
如果您的用户输入完全开放且未经验证,那么 for 循环可能是您最好的选择,如 @glennjackson 的答案中所述。
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.
如果您想要的只是检查 $DBNAME 是否为 $SID 条目,最简单的做法可能是:
请注意 -w 和 -q 是 grep 的非标准选项,因此您可能需要:
如果有的话,这将失败SID 中的条目包含空格,并且
其他奇怪的字符无疑也会引起问题。
If all you want is to check that $DBNAME is an entry is $SID, the easiest thing to do is probably:
Note that -w and -q are non-standard options to grep, so you might want:
This will fail if any of the entries in SID contain spaces, and
other odd characters will undoubtedly cause problems as well.