Command Substitution vs Process Substitution की तुलना
In this page:
variable=$(command)
diff <(command1) <(command2)
Command Substitution Basics
$(command) command execute करता है और खुद को उस command के stdout से replace करता है, एक string के रूप में capture करते हुए जिसमें कोई भी trailing newline हटा दी जाती है, जिसे फिर एक variable को assign किया जा सकता है।
उदाहरण: Command Substitution Basics
#!/bin/bash
today_year=$(date +%Y)
echo "the year variable holds: $today_year"
Login to try C/C++/Java/PHP code in the editor
Process Substitution Basics
<(command) command run करता है और इसके output को एक special path (typically /dev/fd/N) के through expose करता है जिसे दूसरे commands ऐसे पढ़ सकते हैं जैसे यह एक असली file हो, कभी disk पर लिखे बिना।
उदाहरण: Process Substitution Basics
#!/bin/bash
cat <(echo "generated on the fly")
Login to try C/C++/Java/PHP code in the editor
Comparing Two Commands' Output
Process substitution का एक classic उपयोग दो commands के output को सीधे diff में feed करना है जैसे वे files हों, manually temporary files बनाने और clean up करने की ज़रूरत से बचते हुए।
उदाहरण: Comparing Two Commands' Output
#!/bin/bash
diff <(printf "a\nb\nc\n") <(printf "a\nx\nc\n") || echo "differences were found above"
Login to try C/C++/Java/PHP code in the editor
Choosing the Right Tool
Command substitution उपयोग करें जब आपको output एक plain string के रूप में चाहिए (एक variable में store करने या दूसरा string बनाने के लिए); process substitution उपयोग करें जब एक command एक filename argument expect करती है लेकिन आप इसे दूसरी command का live output देना चाहते हैं।
उदाहरण: Choosing the Right Tool
#!/bin/bash
line_count=$(printf "a\nb\nc\n" | wc -l)
echo "captured as text: $line_count lines"
while read -r line; do
echo "from process substitution: $line"
done < <(printf "x\ny\n")
Login to try C/C++/Java/PHP code in the editor
$(...)(command substitution, text produce करता है) को<(...)(process substitution, एक file-like path produce करता है) के साथ confuse करना।- एक POSIX
shscript में process substitution उपयोग करने की कोशिश करना;<(...)एक bash-specific (और कुछ दूसरे shells की) feature है, plainshमें portable नहीं। - यह भूल जाना कि command substitution captured output से trailing newlines strip करता है, जो तब matter कर सकता है जब output की exact formatting significant हो।
$(command)commandrun करता है और इसके stdout को एक string के रूप में substitute करता है, trailing newlines strip की गई।<(command)commandrun करता है और इसके output को एक readable file-like object, अक्सर/dev/fd/N, के path के रूप में expose करता है।- Process substitution commonly दो commands के output को manually temp files बनाए बिना
diffसे compare करने के लिए उपयोग होता है। - दोनों features अपनी command को एक subshell में run करते हैं, इसलिए उनके अंदर set की गई variables बाद में visible नहीं होती।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: