1

I'm using a Bash script to prompt users for several variables before continuing. If I want to create static validation rules and execute them on user inputs in an "a la carte" fashion, how would I go about doing that?

Example:

function q1 () {
  echo "Do you have an answer?"
  read input
  # I know this is wrong but should get the idea across
  chkEmpty($input)
  chkSpecial($input)
}

function chkEmpty () {

    if [[ $input = "" ]]; then
      echo "Input required!"
      # Back to Prompt
    else
      # Continue to next validation rule or question
    fi
}

function chkSpecial () {

    re="^[-a-zA-Z0-9\.]+$"
    if ! [[ $input =~ $re ]]; then
      echo "Cannot use special characters!"
      # Back to prompt
    else
      # Continue to next validation rule or question
    fi
}

function chkSize () {
    etc...
}

etc...

1 Answer 1

3

Functions get their arguments in $1, $2, etc. Also, in shell they're called w/o parentheses, so your code is almost right.

Your function syntax isn't quite right either: You either use parens or the word function. Finally, you can return a result (which works like a process's exit code) with return.

chkEmpty() {
    if [[ "$1" = "" ]]; then
      echo "Input required!"
      return 1 # remember: in shell, non-0 means "not ok"
    else
      return 0 # remember: in shell, 0 means "ok"
    fi
}

Now you can call it like this:

function q1 () {
  echo "Do you have an answer?"
  read input
  chkEmpty $input && chkSpecial $input # && ...
}

Obviously, you'll need to add some code to deal with the invalid input, e.g., by prompting again or aborting the script. If you use while/until and if to check the function's return values, and reprompt or exit.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.