简体   繁体   中英

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
if [ ${a/Source/''} == ${b/Destination/''} ]
then
  # do your job
fi
if [ `echo $a | sed 's/Source\///'` == `echo $b | sed 's/Destination\///'` ]
then
    # Do something
fi

using case/esac

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM