Hojin Lee Hojin Lee - 1 year ago 77
Bash Question

Bash: shell script if statement using multiple conditions including regex

I am currently studying the shell script and having some syntax issue.

what I am tyring is to make the 'if' statement to catch any user-input with alphabet, except the "giveup" line

here is the code that I built:

if [ $usrGuess =~ *[:alpha:]* && $usrGuess != "giveup" ]


once I run the code, it gives out the error message saying that:

[: missing `]'


If you guys have any solution to this, I will be happy to hear your advice :)

Thanks!

Answer Source

test ([) builtin of any shell (or the external one) does not support putting conditional construct e.g. &&, || or multiple command separator e.g. ; inside it.

Also, [ does not support Regex matching with =~. BTW your Regex pattern is not correct, it seems more like a glob pattern (and that should suffice in this case).

Both of the above are supported by the [[ keyword of bash and not all shells support these.

So, you can do:

if [[ $usrGuess = *[:alpha:]* && $usrGuess != "giveup" ]]

Here, I have moved for [[ and used the Glob match $usrGuess = *[:alpha:]* (dropped Regex matching).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download