0

I want to force people to pass a certain string after getting prompted:

while [[ ! ${task} =~ "up|down" ]]; do
    echo $task
    read -p "Task to conduct? [up|down] " input
    task=$input
done

Although passing the correct string I am still getting the prompt:

Task to conduct? [up|down] down
down
Task to conduct? [up|down] up
up
Task to conduct? [up|down] 

What do I miss?

WorkoutBuddy
  • 609
  • 9
  • 23
  • 2
    You can run it through [ShellCheck](https://www.shellcheck.net) to automatically detect common problems including this one – that other guy Nov 25 '20 at 18:07
  • Don't quote the regular expression. Also, that pattern will match anything that just *contains* "up" or "down". Possible duplicate question: [bash regex with quotes?](https://stackoverflow.com/questions/218156/bash-regex-with-quotes) – Gordon Davisson Nov 25 '20 at 18:07
  • 2
    BTW, the more portable way to do this would be with a `case` statement. As in: `case $task in up|down) echo "Task name is valid";; *) echo "Task name is invalid";; esac` -- that'll work even with baseline-standard `/bin/sh`. – Charles Duffy Nov 25 '20 at 18:33

1 Answers1

0

You need to remove the double quotes around the regex. It looks like they are preventing expansion. This works on my box with

#!/usr/bin/env bash
while [[  ! ${task} =~ ^(up|down)$ ]]; do
    read -p "Task to conduct? [up|down] " input
    task=$input
done
Kevin
  • 146
  • 1
  • 8
  • `^(up|down)$` would be more correct. The current regex is unanchored, so it would consider `upside-down` to be a valid answer. – Charles Duffy Nov 25 '20 at 18:32
  • Also, `echo $task` is buggy; it should be `echo "$task"` -- otherwise a `*` would be replaced with a list of filenames, f/e. – Charles Duffy Nov 25 '20 at 18:32
  • 1
    @charles-duffy Thank you for the correction on the regex. I will correct my post. The echo i beleive was just used for debugging – Kevin Nov 25 '20 at 18:35