← Back to Bash Course | Chapter 5: Functions | Lesson 8 of 11

String की तुलना

String comparison यह check करने जैसा है कि दो name tags में एक ही नाम लिखा है या नहीं। Bash यह भी test कर सकता है कि कोई word किसी pattern में fit होता है या नहीं, जैसे 'A से शुरू होता है'।

In this page:

  1. String Comparison
Syntax
bash
[[ "$string1" == "$string2" ]]
[[ "$string1" != "$string2" ]]
[[ "$string1" < "$string2" ]]

String Comparison

[[ ]] के अंदर, strings को == (equal), != (not equal), और lexicographically </> से compare किया जाता है। [[ ]] right side पर एक glob pattern के against == से pattern matching भी support करता है।

String comparison पहले cover किए गए numeric -eq/-lt operators से अलग है।

Warning: Strings को -eq जैसे numeric operators से compare करना गलत या error results देता है — strings के लिए हमेशा ==/!= उपयोग करें।

उदाहरण: String Comparison

bash
#!/bin/bash
a="apple"
b="banana"

if [[ "$a" == "$b" ]]; then
    echo "Equal"
else
    echo "Not equal"
fi

if [[ "$a" == a* ]]; then
    echo "$a starts with 'a'"
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. [ ] के अंदर unquoted variables के साथ = या == उपयोग करना, जो तब टूटता है जब value empty हो या spaces हों।
  2. Strings के लिए -eq उपयोग करना बजाय = के।
  3. = के आस-पास spaces भूल जाना, जैसे [ "$a"="$b" ], जो हमेशा true होता है।

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.