[英]Comparing two variable in shell
我有兩個變量$ a和$ b
和
$a=Source/dir1/dir11
$b=Destination/dir1/dir11
$ a和$ b更改,但首字母Source /和Destination /保持不變。
我想比較沒有來源/和目的地/的$ a和$ b
我該怎么辦? 以下代碼我正在使用
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
但是輸出如下
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
使用case/esac
case "${a#*/}" in
${b#*/} ) echo "ok";;
esac
或用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.