Search code examples
regexbashis-empty

Bash function for zero length string or with whitespace


In bash I can use -z string and -n string to see if the string length is zero or not. Would like to write a bash function that returns true or false, not only if length is zero but also if it is all whitespace. Or is there a way without needing a function?


Solution

  • You can use a regular expression:

    if [[ $string =~ ^" "*$ ]]
    

    or you can remove all the spaces before testing with -z:

    if [[ -z "${string// /}" ]]