![]() |
Bash shell scripting
I need to ask the user a yes or no question. I want to check the answer without being case sensitive. The user might enter y, n, yes, or no, not counting case. How is this typically handled in a bash or sh script? I was thinking of taking the first character of the users input, converting it to lower case and checking for y or n. How can I do this in sh or bash?
|
Have a look at this:
Code:
#!/bin/bash |
Maybe using something like this:
Code:
read -p "Are you a Klingon? [y/n] " ans |
The Linux+ 2nd examination certification objectives says:
Quote:
|
This is posix compliant:
Code:
#!/bin/ash |
@H_TeXMeX_H: I do believe bash needs to be used (have a look at the LPI link).
Besides from that; What exactly determines (bash) POSIX compliance? If I include set -o posix and run my solution (post #2) it works. This about set -o posix / --posix from the bash manual page: Quote:
|
Just change 'ash' to 'bash', I just know that ash is posix compliant, so that's why I wrote it as is.
|
I think this format should be good enough and is compatible with all shells based from the original bourne shell with strict compatibility to it which could include ash, dash, ksh, pdksh and zsh not to mention bash. Note that this is not based from POSIX and should work even though POSIX didn't exist.
Code:
case "$ANSWER" in |
Quote:
Quote:
However when I'm writing scripts for practice, and I don't know how to do something. It's not always clear whether I should look up the bash way of doing it or the standard sh POSIX way doing it. |
@fakie_flip: I hope you considered the example I gave you which doesn't really care if you're running in bash or not, or in POSIX mode or not.
Anyway you actually have at least four choices when writing a script. a) You use bash and pick a minimum version of it for its features like 3.0 or 4.0. b) You follow a syntax that's actually compatible with all shells moreover based from the original shell. So you actually test if your script would work in most shells, or at least all shells that should work the way they should if they strictly base themselves from the original shell; as some shells don't follow well. Note that the POSIX standard is different from this and it (POSIX) was created later to have unity among shells. c) Follow the POSIX standard and hope all shells that supports it have the feature to follow it properly. d) Use other shells. |
Quote:
|
| All times are GMT -5. The time now is 10:44 AM. |