Alex Rivera | Logout

How to check if a string has spaces in Bash shell

Asked 2009-09-24T20:30:33.840
56

Say a string might be like "a b '' c '' d". How can I check that there is single/double quote and space contained in the string?

Edit
Report

2 Answers

3

How about an approach similar to:

$ A="some string"; echo $A | grep \  | wc -l
1
$ A="somestring"; echo $A | grep \  | wc -l
0

?

answered 2009-09-24T20:42:58.120
1
function foo() {
    echo "String: $*"
    SPACES=$(($#-1))
    echo "Spaces: $SPACES"
    QUOTES=0
    for i in $*; do
        if [ "$i" == "'" ]; then
            QUOTES=$((QUOTES+1))
        fi
    done
    echo "Quotes: $QUOTES"
    echo
}

S="string with spaces"
foo $S
S="single' 'quotes"
foo $S
S="single '' quotes"
foo $S
S="single ' ' quotes"
foo $S

yields:

String: string with spaces
Spaces: 2
Quotes: 0

String: single' 'quotes
Spaces: 1
Quotes: 0

String: single '' quotes
Spaces: 2
Quotes: 0

String: single ' ' quotes
Spaces: 3
Quotes: 2
answered 2009-09-24T21:24:26.710

Your Answer