首页 > 解决方案 > Bash比较两个字符串与字符串中的反斜杠

问题描述

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

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

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

你好世界

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

标签: stringbashcomparebackslash

解决方案


不加引号,右手边被当作一个模式,该模式 hello\ world等价于该模式hello world,与文字文本不匹配hello\ world

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

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

推荐阅读