Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a given character is whitespace

Tags:

bash

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!

like image 536
ardevd Avatar asked Oct 21 '25 14:10

ardevd


1 Answers

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
like image 186
John B Avatar answered Oct 23 '25 06:10

John B