问题
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