SSen23
SSen23

Reputation: 39

How to check for space in a variable in bash?

I am taking baby steps at learning bash and I am developing a piece of code which takes an input and checks if it contains any spaces. The idea is that the variable should NOT contain any spaces and the code should consequently echo a suitable message.

Upvotes: 4

Views: 6641

Answers (5)

Toby Speight
Toby Speight

Reputation: 30901

You can test simple glob patterns in portable shell by using case, without needing any external programs or Bash extensions (that's a good thing, because then your scripts are useful to more people).

#!/bin/sh

case "$1" in
    *' '*)
        printf 'Invalid argument %s (contains space)\n' "$1" >&2
        exit 1
        ;;
esac

You might want to include other whitespace characters in your check - in which case, use *[[:space:]]* as the pattern instead of *' '*.

Upvotes: 2

Benjamin W.
Benjamin W.

Reputation: 52346

You could use parameter expansion to remove everything that isn't a space and see if what's left is the empty string or not:

var1='has space'
var2='nospace'

for var in "$var1" "$var2"; do
    if [[ ${var//[^[:space:]]} ]]; then
        echo "'$var' contains a space"
    fi
done

The key is [[ ${var//[^[:space:]]} ]]:

  • With ${var//[^[:space:]]}, everything that isn't a space is removed from the expansion of $var.
  • [[ string ]] has a non-zero exit status if string is empty. It's a shorthand for the equivalent [[ -n string ]].

We could also quote the expansion of ${var//[^[:space:]]}, but [[ ... ]] takes care of the quoting for us.

Upvotes: 1

cn0047
cn0047

Reputation: 17091

You can use grep, like this:

echo " foo" | grep '\s' -c
# 1
echo "foo" | grep '\s' -c
# 0

Or you may use something like this:

s=' foo'
if [[ $s =~ " " ]]; then
    echo 'contains space'
else
    echo 'ok'
fi

Upvotes: 5

kiner_shah
kiner_shah

Reputation: 4641

You can use wc -w command to check if there are any words. If the result of this output is a number greater than 1, then it means that there are more than 1 words in the input. Here's an example:

#!/bin/bash
read var1
var2=`echo $var1 | wc -w`
if [ $var2 -gt 1 ]
then
    echo "Spaces"
else
    echo "No spaces"
fi

Note: there is a | (pipe symbol) which means that the result of echo $var1 will be given as input to wc -w via the pipe.

Here is the link where I tested the above code: https://ideone.com/aKJdyN

Upvotes: 1

Incrivel Monstro Verde
Incrivel Monstro Verde

Reputation: 948

Try this:

#!/bin/bash
if [[ $1 = *[[:space:]]* ]]
then
    echo "space exist"
fi

Upvotes: 4

Related Questions