views:

82

answers:

3

How can I test if some string is dot in bash? I've tried this:

if [ "$var" = "." ]

and this:

if [ "$var" = "\." ]

But it doesn't work.

A: 

Try doubling the equals (==), comparing is not the same as assigning.

unwind
Thanks. that o the trick
kofucii
In Bourne/bash, the = operator is used for both.
Ray
-eq can only be used for integer comparison. = needs to be used for strings.
Ray
@Ray, I was speaking in general, but you are correct. When comparing integers, =, == and -eq do the same thing in bash.
Tim Post
+4  A: 

Works for me:

$ d=.
$ if [ $d = '.' ];then echo 'yes'; else echo 'no'; fi
yes
$ d=foo
$ if [ $d = '.' ];then echo 'yes'; else echo 'no'; fi
no
Mark Byers
+1  A: 

My code:

#!/bin/bash

var="."

[ $var = "." ] && echo "Yup, it equals '.'"

exit 0

Which prints:

Yup, it equals '.'

Debugged:

tpost@tpost-desktop:~$ /bin/bash -x ./foo.sh
+ var=.
+ '[' . = . ']'
+ echo 'Yup, it equals '\''.'\'''
Yup, it equals '.'
+ exit 0

You probably have some white space in $var (or perhaps $var is empty?), run it through /bin/sh -x ./yourscript.sh to see what its actually comparing.

Keep in mind, == is a bashism, it only works in Bash. Its there as a creature comfort for people who are used to a single = resulting in an assignment.This is fine if you are only using bash, but you never know what /bin/sh on some systems may point to. Its better to just use = and avoid the problem altogether.

Tim Post