0

I am a newbie in shell script. I see if condition with and without brackets as shown below. When do we go for if condition with and without brackets?

if [[ $(kubectl get pods -n kube-system -l app.kubernetes.io/name=node --no-headers | wc -l) != "$_node_count" ]]; then
        echo "error"
        kubectl get pods -n kube-system -l app.kubernetes.io/name=node
        exit 1
    fi
 
    if kubectl get pods -n kube-system -l app.kubernetes.io/name=node --no-headers | grep -v Running; then
        echo "not running"
        kubectl get pods -n kube-system -l app.kubernetes.io/name=node
        exit 1
    fi
Rad4
  • 1,936
  • 8
  • 30
  • 50
  • In general, don't think of brackets as shell syntax. `/usr/bin/[` is a _command_, the same command documented in `man test`, and `[` has the same parsing rules as any other command. Even though the shell has a built-in version of `[` as a performance enhancement, and `[[` is built-in only and has its own parsing rules that make it easier to use, it's still often useful to think of `[[` as an extended version of the `[` command. – Charles Duffy Mar 14 '22 at 21:39
  • Anyhow, an `if` **always** tests whether the command or pipeline it contains has a zero or nonzero exit status. That's true if that command being tested is `[[` as it is when the command being tested is `grep`. Both `[[` and `grep` are commands, and they both have an exit status that is either truthy or falsey. – Charles Duffy Mar 14 '22 at 21:40
  • As an addendum to the linked duplicate, see [BashFAQ #31](https://mywiki.wooledge.org/BashFAQ/031) discussing the differences between `[[` and `[`. – Charles Duffy Mar 14 '22 at 21:42
  • https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html is the POSIX specification for `[`. As it says, in the 1-argument case the operation it performs is checking whether the string it receives is nonempty; so `[ "$(something)" ]` checks whether `something` has non-empty output. `[[ $(something) ]]` is the same, but it implicitly turns off string-splitting and globbing so you don't need the double quotes for correct operation. – Charles Duffy Mar 14 '22 at 21:47
  • Be specific which shell you are talking about. You tagged it _shell_, which means POSIX shell, and there you don't have double-brackets. Your commands would make sense in zsh, or ksh, or bash. – user1934428 Mar 15 '22 at 07:39

0 Answers0