【问题标题】:Comparing two variable in shell比较shell中的两个变量
【发布时间】:2011-04-14 03:30:13
【问题描述】:

我有两个变量 $a 和 $b

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

$a 和 $b 发生变化,但 Source/ 和 Destination/ 的首字母保持不变。
我想比较 $a 和 $b 而没有 Source/ 和 Destination/

我应该怎么做? 以下代码我正在使用

   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

【问题讨论】:

  • 仅供参考,您实际上并没有在该表达式中分配任何内容。丢掉美元符号来做作业。
  • 'Source' 和 'Destination' 的名称是固定的,还是它们的路径保存在变量中?这可能会影响最佳答案。
  • 即使它像 $a=Source/dir1/dir11/mydir 一样发生变化,我也想比较。我总是想在没有 Source/ 和 Destination/ 的情况下进行比较
  • 如果 [ ${a/Source\//''} == ${b/Destination\//''} ]

标签: linux shell scripting


【解决方案1】:
if [ ${a/Source/''} == ${b/Destination/''} ]
then
  # do your job
fi

【讨论】:

  • 如果 $a=Source/dir1/dir11/mydir 则不进行比较。我总是想在没有 Source/ 和 Destination/ 的情况下进行比较
  • 将其更改为 if [ ${a/Source\//''} == ${b/Destination\//''} ]
  • @Hellboy:当您对 shell 的理解不够好,无法识别正确答案时,这对您来说效果不佳。我建议您查找并完成一些基本的脚本教程。
  • @Tony 我真的告诉​​过我知道的不多,但我必须这样做,而且我的时间更少。
【解决方案2】:
if [ `echo $a | sed 's/Source\///'` == `echo $b | sed 's/Destination\///'` ]
then
    # Do something
fi

【讨论】:

  • 使用 '$(...)' 比使用反引号更好。此外,bash 有一个 '<<<' 运算符来避开管道。
【解决方案3】:

使用case/esac

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

【讨论】:

    【解决方案4】:

    或者用 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
    

    【讨论】:

    • 你可以使用'<<<'来避免echo | awk管道。此外,basea 将包含 Source,baseb 将包含 Destination;您需要打印除$1 之外的所有内容。如果 Source 实际上是 /mnt/usb-stick/installation/path 而 Destination 实际上是 /opt/SomeBody/Program,就会出现问题。我也不确定为什么 IFS 中有反斜杠。
    猜你喜欢
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多