0

I am trying to validate multiple inputs separated by spaces(two disk names in the below case) with a shell script. But, I am un-successful in doing so. Can someone help me?

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

2 Answers 2

1

For ksh93, you can use

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

For ksh88, use the positional parameters

read disks
set -- $disks
if [[ $# -ne 2 ]]; then
    print -u2 "You need to enter 2 disks" 
    exit 1
else
    print "You entered: $disks"
fi
Sign up to request clarification or add additional context in comments.

2 Comments

It did work out. But can you let me know the pupose you have used set --
That invokation of set, with no other ±options, sets the positional parameters to the values you provide. So now, $1 is the first word, $2 is the second word, etc.
0

The variables ${1} and ${2} are the commandline parameters and are unrelated to the last read command. There are different ways to use the DISK variable. Once you have the DISK variable read, I would have chosen for a solution like

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)

When you already know you want to split the fields, you can change your first read command. Replace read DISK with

read disk1 disk2 remaining_input

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.