ardevd
ardevd

Reputation: 3407

Check if a given character is whitespace

In my script I take a string, loop through each character and pass it into a function which uses a switch case to check what character it is and act accordingly. It works fine, but it doesnt seem to be able to match whitespace characters. What notation can I use?

NOTE: Only a single character will be passed into this function, so I only need to figure out if this single character is a whitespace character.

Snippet from the code

    " ")
        doSomething
        ;;
    "a")
        doSomethingElse
        ;;
    "b")
        doSomethingElse
        ;;
    "c")
        doSomethingElse
        ;;

Also tried

    *\ * )
        tap 388 1127
        ;;

Thanks!

Upvotes: 4

Views: 3962

Answers (1)

John B
John B

Reputation: 3646

In BASH, you can use POSIX character classes to match whitespace with [[:space:]].

case $var in
    [[:space:]])
        doSomething
        ;;
esac

The [[:space:]] will match any whitespace character.

Testing for character classes can also be done inside double brackets:

[[ $var == [[:space:]] ]] && doSomething

Upvotes: 12

Related Questions