验证通过读取命令获得的多个输入

Validating multiple inputs procured through read command

我正在尝试使用 shell 脚本验证以空格分隔的多个输入(在下面的例子中是两个磁盘名称)。但是,我这样做并不成功。有人能帮我吗?

read DISK
if [ "" = "" ] || [ "" = "" ]
then
printf "The Disk pairs cannot be left blank. Exiting script!!!"
exit 1
else
TMP=$DISK
printf "The disks entered are $TMP"
fi

对于ksh93,可以使用

read -A disks
if [[ ${#disks[@]} -ne 2 ]]; then
    print -u2 "You need to enter 2 disks" 
    exit 1
else
    print "You entered: ${disks[*]}"
fi

对于 ksh88,使用位置参数

read disks
set -- $disks
if [[ $# -ne 2 ]]; then
    print -u2 "You need to enter 2 disks" 
    exit 1
else
    print "You entered: $disks"
fi

变量</code>和<code>是命令行参数,与上次读取命令无关。有多种使用 DISK 变量的方法。 读取 DISK 变量后,我会选择

这样的解决方案
echo "${DISK}" | while read disk1 disk2 otherfields; do
   echo "disk1=${disk1}, disk2=${disk2}"
done
# or better
disk1="${DISK% *}"; echo "${disk1}"
disk2="${DISK#* }"; echo "${disk2}"
# or worse
disk1=$(echo "${DISK}" | cut -d" " -f1)
disk2=$(echo "${DISK}" | cut -d" " -f2)

当您已经知道要拆分字段时,您可以更改第一个读取命令。将 read DISK 替换为

read disk1 disk2 remaining_input