How to detect spaces in shell script variable

eg string = "test test test"

I want that after detecting any space in the line, it should echo and exit the else process.

+4
source share
6 answers

The operator caseis useful in such cases:

case "$string" in 
    *[[:space:]]*) 
        echo "argument contains a space" >&2
        exit 1
        ;; 
esac

Manages leading / trailing spaces.

+2
source

For a pure Bash solution:

function assertNoSpaces {
    if [[ "$1" != "${1/ /}" ]]
    then
        echo "YOUR ERROR MESSAGE" >&2
        exit 1
    fi
}

string1="askdjhaaskldjasd"
string2="asjkld askldja skd"

assertNoSpaces "$string1"
assertNoSpaces "$string2" # will trigger error

"${1/ /}" removes any spaces in the input line, and compared to the original line should be exactly the same if there are no spaces.

Pay attention to the quotes around "${1/ /}"- This ensures that leading / trailing spaces are taken into account.

, , - "${1/[ \\.]/}".

. , , .

function assertNoSpaces {
    if [[ "$1" =~ '[\. ]' ]]
    then
        echo "YOUR ERROR MESSAGE" >&2
        exit 1
    fi
}

=~ . Bash Scripting.

Bash 3, , Bash.

2

:

,    "asd \"   ... ?

, , , , .

, read, , , escape-, , . .

read str              # user enters "abc\"
echo $str             # prints out "abc", not "abc\"
assertNoSpaces "$str" # no error since backslash not in variable

, -r . . MAN.

read -r str           # user enters "abc\"
echo $str             # prints out  "abc\"
assertNoSpaces "$str" # triggers error
+1

grep :

string="test test test"
if ( echo "$string" | grep -q ' ' ); then
        echo 'var has space'
        exit 1
fi
0

; - :

if [ "$string" != "${string% *}" ]; then
     echo "$string contains one or more spaces";
fi
0

The operator ==in double brackets can match wildcard characters.

if [[ $string == *' '* ]]
0
source

I just ran into a very similar problem when handling paths. I decided to rely on expanding my shell options, rather than specifically looking for space. It does not detect space in the front or the end, though.

function space_exit {
  if [ $# -gt 1 ]
  then
    echo "I cannot handle spaces." 2>&1
    exit 1
  fi
}
-1
source

Source: https://habr.com/ru/post/1780410/


All Articles