Validate the number of arguments passed in bash from read

半腔热情 提交于 2021-02-05 06:06:18

问题


I have a question about validating user input regarding number of arguments passed by the user in a bash script. For example, if I use:

if [[ $# -eq 2 ]]
then...

that will check if 2 arguments passed from the command line like this:

./somescript.sh arg1 arg2

but how to validate if user passed 2 arguments when asked? For example:

echo "Type 2 names:"
read...
if [[ user passed more || less than 2 arguments]]
   echo "incorrect number of names"

Now if I try to use $# -eq 2 it doesn't work.

What's the proper way to do it?


回答1:


Use an array:

read -r -a array
if [[ "${#array[@]}" -eq 2 ]]; then ...

See output of:

declare -p array



回答2:


Alternatively if your shell has no array like ksh or POSIX shell, you can populate the arguments from the read variable like this:

read -r reply
set -f # Disable globbing
set -- $reply # without quotes
if [ $# -eq 2 ]; then


来源:https://stackoverflow.com/questions/60909805/validate-the-number-of-arguments-passed-in-bash-from-read

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!