1

So I'm having a bit of a problem when running this command in bash;

echo "$usr_age" | grep "^[0-9]*$" > $null || echo "Please only use numbers in the Age field." || exit 1

When running it, if the "$usr_age" variable has anything that is not a number, it warns the user, but it doesn't exit the script. I also tried changing the last || to && but if I do so it will just exit the script even if the variable is all numbers.

Note: the "$null" variable is just "/dev/null"

Thank you.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
DarviL
  • 13
  • 4

1 Answers1

2

Use a grouping operator to combine the echo and the exit. a || b runs b only if a fails, whereas you want to run exit whether or not echo succeeds.

grep -q "^[0-9]*$" <<<"$usr_age" || { echo "Only use numbers in the Age field."; exit 1; }

By the way -- grep, as an external command, is quite slow to start up compared to using a shell builtin. Consider instead bash's built-in regex support:

[[ $usr_age =~ ^[0-9]*$ ]] || { echo "Only use numbers in the Age field."; exit 1; }
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Thank you! It works perfectly now. I didn't think about grouping them. Also I didn't know about that regex operator, very cool! – DarviL Nov 30 '20 at 20:43
  • BTW, the reason to use `grep -q` instead of `grep >/dev/null` is that `-q` is faster -- it can exit the moment it sees a match, instead of needing to read to the end of input (and write matches to `/dev/null` -- which is fast compared to writing to actual disk, but it's still a switch between userland and kernelspace for every write, so they're not completely free). That's not a big difference for a one-line input, of course, but it's a good habit to be in for when you're searching in a larger file. – Charles Duffy Dec 03 '20 at 14:01