Domanda

I wrote this script in Unix:

function addinfo {
  echo "Please enter your LAST Name: "
  read last
  echo "Please enter your FIRST Name: "
  read first
  echo "Please enter your PHONE number as XXX-XXX-XXXX: "
  read phone
  if [ $phone != ???-???-??? ]; then
    echo "Please only enter your as XXX-XXX-XXXX"
    read phone
  else
    echo $last + $first + $phone >> asg7phonebook
  if
}

I'm getting an error code associated with the last bracket.

  1. Can boolean conditions work inside a Unix function?
  2. How do I get my function to check whether the user entered XXX-XXX-XXXX (where "X" is their phonenumber) as a valid number input? I want to prevent the user from entering 23435-34222 as their number or 1234567890 as their number.
  3. Is my syntax correct?
È stato utile?

Soluzione

I see a few issues with your approach,

#!/usr/bin/env ksh

addinfo() {
  echo "Please enter your LAST Name: "
  read last
  echo "Please enter your FIRST Name: "
  read first
  echo "Please enter your PHONE number as XXX-XXX-XXXX: "
  read phone
  # Using a while loop on the correct pattern check.
  while [[ "$phone" != [0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9] ]]
  do
      echo "Please enter your PHONE number as XXX-XXX-XXXX (only): "
      read phone
  done
  echo $last + $first + $phone >> asg7phonebook
}

addinfo

Altri suggerimenti

#!/bin/bash
function addinfo() {
  echo "Please enter your LAST Name: "
  read last
  echo "Please enter your FIRST Name: "
  read first
  echo "Please enter your PHONE number as XXX-XXX-XXXX: "
  read phone
  if [[ $phone =~ ^[0-9]{3}-[0-9]{3}-[0-9]{4}$ ]]; then
    echo $last:$first:$phone >> asg7phonebook
  else
    echo "Please only enter your as XXX-XXX-XXXX"
  fi
}

addinfo

@Elliott Frisch's answer is a working solution, but just to show a simpler matching option using ksh 93's extended patterns:

[[ $phone == {3}(\d)-{3}(\d)-{4}(\d) ]]  # matches '123-456-7890', for instance

Courtesy of: https://stackoverflow.com/a/5523776/45375

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top