0

Referring to this https://stackoverflow.com/a/31356602, I wrote this code:

#!/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"

that returns:

enter image description here

Now I'm trying to condensate it in a single line:

#!/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")

but I get:

enter image description here

How can I pass strings as files to git diff without explicitly creating temporary files?

Note. My goal is to "visually" compare (character-level) two (short) strings, obtaining an output similar to this:

enter image description here

in which the differences between the two compared strings are highlighted in a single string. The output of git diff is ideal, but I am also open to other solutions.

1 Answer 1

1

This won't be possible with pipe-based redirection as in your bash's <().

But: with zsh-isms, it should work. There is the temporary file expansion =():

#!/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")

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .