Vivek
Vivek

Reputation: 4260

Comparing two variable in shell

I have two variables $a and $b

and

$a=Source/dir1/dir11
$b=Destination/dir1/dir11

$a and $b changes but initials Source/ and Destination/ remains same.
I want to compare $a and $b without Source/ and Destination/

how should I do it? Following code I am using

   SOURCE_DIR_LIST=`find Source/ -type d`
   DEST_DIR_LIST=`find Destination/ -type d`

for dir_s in $SOURCE_DIR_LIST
do
    for dir_d in $DEST_DIR_LIST
    do

        if [ ${dir_s/Source\//''} == ${dir_d/Destination\//''} ]
        then
                echo " path match = ${dir_s/Source\//''}"

        else
             echo "path does not match source path = ${dir_s/Source\//''} "
             echo " and destination path= ${dir_d/Destination\//''} "
        fi
    done
done

But output is coming like as follow

 path match = ''
./compare.sh: line 9: [: ==: unary operator expected
path does not match source path = ''
 and destination path= ''dir2
./compare.sh: line 9: [: ==: unary operator expected
more

Upvotes: 1

Views: 3281

Answers (4)

kurumi
kurumi

Reputation: 25599

using case/esac

case "${a#*/}" in
 ${b#*/} ) echo "ok";;
esac

Upvotes: 1

Neo
Neo

Reputation: 5463

if [ ${a/Source/''} == ${b/Destination/''} ]
then
  # do your job
fi

Upvotes: 4

matcheek
matcheek

Reputation: 5147

or with awk

 #!/bin/bash
    a="Source/dir1/dir11"
    b="Destination/dir1/dir11"
    SAVEIFS=$IFS
    IFS="\/"
    basea=$(echo $a | awk '{print $1}')
    baseb=$(echo $b | awk '{print $1}') 
    if [ $basea == $baseb ]; then
        echo "Equal strings"
    fi
    IFS=$SAVEIFS

Upvotes: 0

Chris Eberle
Chris Eberle

Reputation: 48765

if [ `echo $a | sed 's/Source\///'` == `echo $b | sed 's/Destination\///'` ]
then
    # Do something
fi

Upvotes: 1

Related Questions