• Ephera@lemmy.ml
    link
    fedilink
    English
    arrow-up
    2
    ·
    2 months ago

    Here’s an example, I have looked up many times (like just now), which checks whether a string is empty:

    var=""
    if [ -z "$var" ]; then
        echo "empty"
    else
        echo "not empty"
    fi
    

    Why -z? I have no idea. I will also routinely forget the ]; then part. I believe, if you write the then onto the next line, then you don’t need the semicolon. And then someone’s probably gonna tell me to use double-brackets [[ ]] instead, which probably does something.

    Arguably, I never fully learned Bash syntax, but it also is just a stupid if-statement. There shouldn’t be that much complexity in it.

    • balsoft@lemmy.ml
      link
      fedilink
      arrow-up
      4
      ·
      edit-2
      2 months ago

      Why -z? I have no idea.

      From man test (note that [ <expr> ] is just sugar for test <expr>):

             -n STRING
                    the length of STRING is nonzero
      
             -z STRING
                    the length of STRING is zero
      

      So, -z stands for Zero.

      Hope this helps you remember it!

    • Anna@lemmy.ml
      link
      fedilink
      arrow-up
      2
      ·
      2 months ago

      -z means zero length and mostly [[ ]] are used when you want to add multiple conditions. But there are also few test cases which are only in bash so they also need double brackets