Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string has spaces in Bash shell

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?

like image 249
derrdji Avatar asked Sep 24 '09 20:09

derrdji


People also ask

How do I check if a string is empty in bash?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"

What does =~ mean in bash?

A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator.

How do you handle spaces in bash?

Filename with Spaces in Bash A simple method will be to rename the file that you are trying to access and remove spaces. Some other methods are using single or double quotations on the file name with spaces or using escape (\) symbol right before the space.

What is the space character in bash?

Char. Whitespace — this is a tab, newline, vertical tab, form feed, carriage return, or space. Bash uses whitespace to determine where words begin and end. The first word is the command name and additional words become arguments to that command.


2 Answers

You can use regular expressions in bash:

string="a b '' c '' d" if [[ "$string" =~ \ |\' ]]    #  slightly more readable: if [[ "$string" =~ ( |\') ]] then    echo "Matches" else    echo "No matches" fi 

Edit:

For reasons obvious above, it's better to put the regex in a variable:

pattern=" |'" if [[ $string =~ $pattern ]] 

And quotes aren't necessary inside double square brackets. They can't be used on the right or the regex is changed to a literal string.

like image 126
Dennis Williamson Avatar answered Oct 07 '22 21:10

Dennis Williamson


case "$var" in        *\ * )            echo "match"           ;;        *)            echo "no match"            ;; esac 
like image 41
Steve B. Avatar answered Oct 07 '22 21:10

Steve B.