3

I tried this, but it doesn't work.

if [ $char -eq " " -o $char -eq "" -o $char -eq "   " ]
3
  • What do you want to do with that comparison. Are you trying to remove white space from lines in a file? Commented Apr 5, 2018 at 9:41
  • No, i just want to skip them Commented Apr 6, 2018 at 19:12
  • How to check if a string has spaces in Bash shell Commented Aug 3, 2018 at 17:16

4 Answers 4

1

-eq is for numerics. Also, you should enclose the variable in quotes, such as "$char", not $char

#! /bin/sh

A=1
B=" "

if [ "$A" -eq 1 ]; then
    echo "eq is for numeric"
fi

if [ "$B" = " " ]; then
    echo "= is for characters"
fi
Sign up to request clarification or add additional context in comments.

Comments

1

This works for single char variable $char, but note that the post assumes mainly a multi-char variable.

Use:

if grep -q '\s' <<< "$char"; then ...

Comments

1

-eq for numeric value, for string, use ==

if [[ $char == " " || -z $char || $char == "   " ]]; then
  • -z equivalent ""
  • || equivalent -o

regex alternative with recent bash ( 0 or 1 space or 3 spaces ):

if [[ $char =~ ^\ {0,1}$ || $char =~ ^\ {3}$ ]] ; then
  • \ : space only
  • [[:blank:]] : space, tab
  • [[:space:]] : space, tab, newline, vertical tab, form feed, carriage return
  • if you want to match 0 to 3 spaces: if [[ $char =~ ^\ {0,3}$ ]] ; then

Comments

0

In bash you can use regex match in [[]]

if  [[ $char =~ [[:space:]] ]]

If you actually want to match a single whitespace character

if  [[ $char =~ ^[[:space:]]$ ]]

Or single whitespace or nothing

if  [[ $char =~ ^[[:space:]]?$ ]]

Or only whitespace in a string

if  [[ $char =~ ^[[:space:]]+$ ]]

Or only whitespace or nothing

if  [[ $char =~ ^[[:space:]]*$ ]]

4 Comments

char='a a' matches...
@kyodev Why wouldn't it?
@kyodev Not sure what you mean?
@kyodev Question asks for whitespace, [[:space:]] is a character class for whitespace. Note that the code in the question is just what OP tried, not necessarily exactly what they want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.