Search code examples
bashscriptingglob

Multiple Conditionals and globbing in Bash


So have I got this right? In Bash, I can use globbing to test strings for patterns if I use double-brackets around the condition:

if [[ $var = abc* ]]

and I can test for multiple conditions if I use single brackets:

if [ $var = abc123 -o $var = abc456 ]

but there's no way I can do both together?

I'm using Bash v3.0, so it doesn't recognize regex's or the =~ operator.


Solution

  • The use of -o is deprecated by the POSIX standard. For POSIX compatibility, use two separate test commands:

    if [ "$var" = abc123 ] || [ "$var" = abc456 ]
    

    In bash, you can do the same, with either [ ... ] or [[ ... ]] commands, or use || inside a [[ ... ]] command:

    if [ "$var" = abc123 ] || [ "$var" = abc456 ]  # POSIX compatible
    
    # No reason to use either of the next three, but the syntax is valid
    if [[ "$var" = abc123 ]] || [ "$var" = abc456 ]
    if [ "$var" = abc123 ] || [[ "$var" = abc456 ]]
    if [[ "$var" = abc123 ]] || [[ "$var" = abc456 ]]
    
    if [[ "$var" = abc123 || "$var" = abc456 ]]    # Preferred for bash