【问题标题】:Bash compare two strings with backslash in stringBash比较两个字符串与字符串中的反斜杠
【发布时间】:2019-05-08 10:31:42
【问题描述】:

这不是我的确切问题,但为了简单起见,我们开始吧。

如果我运行以下命令,我需要它来返回文件匹配,但由于某种原因,如果我的字符串中包含反斜杠,它总是会失败。

文件 testmonitor.txt 仅包含以下文本

你好\世界

#!/bin/bash
file=$(cat /tmp/testmonitor.txt)
if [[ $file == $file ]]; then  
     echo "files match"   
else  
    echo "files not matching"  
fi

【问题讨论】:

    标签: string bash compare backslash


    【解决方案1】:

    不加引号,右侧视为模式,模式hello\ world等价于模式hello world,与文字文本hello\ world不匹配。

    引用右侧以确保执行精确的字符串比较而不是模式匹配。

    if [[ $file == "$file" ]];
    

    【讨论】:

      【解决方案2】:

      通常在双引号中设置变量可以解决此类问题

      if [[ "$file" == "$file" ]]; then  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-07
        • 1970-01-01
        • 2010-10-13
        • 2011-08-01
        • 2015-06-17
        • 1970-01-01
        • 2015-11-24
        相关资源
        最近更新 更多