Why is double bracket used to 'ensure' some commands, since it is not a logical check for "does it exist or not' (false/true)?

Recently I’ve been trying to figure out more and more shell syntax and logic behind some lines within scripts and I have the following question:
What is the purpose of [[expression]] in the example since it brings no value to the executed line and can thus be skipped and done just with the actual expression after [[]]?.

export SDKMAN_DIR="$HOME/.sdkman"
[[ -s "$HOME/.sdkman/bin/sdkman-init.sh" ]] && source "$HOME/.sdkman/bin/sdkman-init.sh"

My presumption is that it is some kind of check in case some value is missing (Null pointer exception) , but I don’t think the "[[]]" operators does something like that?
Goal of the script is simple => to export sdk to be available globally from the terminal.

The -s file conditional expression checks whether the named file exists and is not empty. The [[…]] compound command exits with an appropriate status depending on the evaluation of the expression inside the double brackets.

Thus

[[ -s "$HOME/.sdkman/bin/sdkman-init.sh" ]] && source "$HOME/.sdkman/bin/sdkman-init.sh"

only sources $HOME/.sdkman/bin/sdkman-init.sh if it exists and is not empty.

(I’m assuming export SDKMAN_DIR="$HOME/.sdkman" is on a separate line.)

Answered By: Stephen Kitt

On my local machine (and from experience) ‘[‘ is an alias in bash for /usr/bin/test. Clearly [[ does not expand to /usr/bin/test/usr/bin/test (because there’s no space between). In bash (and possibly other shells) double square brackets are a reserved word that use the shells internal expression evaluator rather than calling /usr/bin/test.

The code here executes $HOME/.sdkman/bin/sdkman-init.sh in the current shell if the file has a non-zero length after setting a variable. I have no idea what the intention of doing this is (since a zero length file wouldn’t actually do anything).

Answered By: symcbean
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.