在不为 git diff 显式创建临时文件的情况下执行“字符串”的字符级比较

在不为 git diff 显式创建临时文件的情况下执行“字符串”的字符级比较

参考这个https://stackoverflow.com/a/31356602,我写了这样的代码:

#!/bin/bash

# Define the two strings to compare
string1="First string with some random text."
string2="Second string with some random text and some changes."

# Create a temporary directory
temp_dir=$(mktemp -d)

# Create temporary files for the strings
file1="$temp_dir/string1.txt"
file2="$temp_dir/string2.txt"
echo -e "$string1" > "$file1"
echo -e "$string2" > "$file2"

# Use the git diff command to compare the temporary files
git diff --no-index --word-diff=color --word-diff-regex=. "$file1" "$file2"

# Delete the temporary directory
rm -rf "$temp_dir"

返回:

在此输入图像描述

现在我试图将它压缩成一行:

#!/bin/bash

# Define the two strings to compare
string1="First string with some random text."
string2="Second string with some random text and some changes."

# Use the git diff command to compare the strings
git diff --no-index --word-diff=color --word-diff-regex=. <('%s\n' "$string1") <(printf '%s\n' "$string2")

但我得到:

在此输入图像描述

如何在git diff不显式创建临时文件的情况下将字符串作为文件传递?

笔记。我的目标是“直观地”比较(字符级)两个(短)字符串,获得与此类似的输出:

在此输入图像描述

其中两个比较字符串之间的差异在单个字符串中突出显示。的输出git diff是理想的,但我也愿意接受其他解决方案。

答案1

使用基于管道的重定向(如 bash 的<().

但是:使用 zsh-isms,它应该可以工作。有临时文件扩展=()

#!/usr/bin/zsh
# use zsh instead of bash

# Define the two strings to compare
string1="First string with some random text."
string2="Second string with some random text and some changes."

# Use the git diff command to compare the strings
git diff \
    --no-index \
    --word-diff=color --word-diff-regex=. \
    =(printf '%s\n' "$string1") \
    =(printf '%s\n' "$string2")

相关内容