← Back to Bash Course | Chapter 13: Advanced Scripting | Lesson 3 of 7

Process Substitution व्यवहार में (diff <(...) <(...))

आप दो अलग commands के results सीधे compare कर सकते हैं, जैसे वे दो files हों, उन्हें कभी पहले disk पर save किए बिना।
Syntax
bash
diff <(command1) <(command2)

दो Command Outputs Compare करना

diff <(cmd1) <(cmd2) आपको दो commands के live output को सीधे diff करने देता है, जो manually हर एक को एक temp file में redirect करने, उन्हें diff करने, और बाद में clean up करने से कहीं ज़्यादा convenient है।

उदाहरण: Comparing Two Command Outputs

bash
#!/bin/bash
diff <(printf "a\nb\nc\n") <(printf "a\nb\nc\n") && echo "identical output, no differences"

एक Difference Detect करना

diff का exit status एक उपयोगी signal भी है: 0 मतलब कोई difference नहीं, 1 मतलब differences मिले, जो एक script को comparison result पर directly branch करने देता है।

उदाहरण: Detecting a Difference

bash
#!/bin/bash
if diff <(printf "a\nb\n") <(printf "a\nc\n") > /dev/null; then
    echo "no differences"
else
    echo "differences were found"
fi

Data के Sorted Versions Compare करना

Process substitution दूसरी pipelines के साथ अच्छी तरह compose होता है; दो data sets के sorted output compare करना यह check करने का एक common real-world उपयोग है कि दो lists order चाहे जो भी हो same elements रखती हैं या नहीं।

उदाहरण: Comparing Sorted Versions of Data

bash
#!/bin/bash
list_a="banana\napple\ncherry"
list_b="cherry\nbanana\napple"
if diff <(printf "$list_a" | sort) <(printf "$list_b" | sort) > /dev/null; then
    echo "both lists contain the same elements"
fi
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. उन commands के साथ process substitution उपयोग करने की कोशिश करना जिन्हें एक pipe-like descriptor के बजाय एक असली seekable file चाहिए; कुछ tools इसे support नहीं करते।
  2. यह भूल जाना कि diff differences मिलने पर एक non-zero exit status return करता है, जो expected behavior है, कोई error नहीं।
  3. एक POSIX sh script में process substitution उपयोग करना और confused होना कि यह क्यों fail होता है; यह एक bash (और कुछ दूसरी shells) का extension है।
चैप्टर सारांश
  • diff <(cmd1) <(cmd2) बिना intermediate temp files के दो commands का live output compare करता है।
  • diff inputs identical होने पर 0 और differ होने पर 1 exit करता है, जो scripts directly check कर सकती हैं।
  • Process substitution जहां भी एक filename expected हो वहां उपयोग किया जा सकता है, सिर्फ diff के साथ नहीं।
  • हर <(...) अपना command एक subshell में run करता है, इसलिए यह calling script को वापस variables leak नहीं कर सकता।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.