On 7/1/25 10:41 PM, Grant Edwards wrote:
> On 2025-07-02, Eli Schwartz <eschwa...@gentoo.org> wrote:
> 
>> if [ "$?" -eq "0" ] ; then
>>     echo "Crypt file system is open"
>> else
>>     echo "Crypt is not open.  Please enter passphrase."
>>     cryptsetup open $LVM_DEV crypt
>> fi
>>
>> This makes your eyes get drawn to the lines that are aligned left, which
>> have the "when shall I run it?" logic. You can easily tell that
>> "cryptsetup open" happens AFTER the "else".
> 
> Maybe it's just me, but I've switched from using [ ] to [[ ]].  I find
> it works right the first try way more often. It's a bash built-in, and
> the quoting and whitespace handling seems to work more like my brain
> expects.  After decades of using [ ], I was still regularly tripped up
> in ways that I don't seem to be using [[ ]].


Yes, in general [[ is better than [

The practical difference is that it is parsed as a keyword, not as an
ordinary command, hence it knows what is inside of it without whitespace
handling. i.e.

[[ $FOO = bar ]]

$FOO does not need quotes because [[ runs *before* word splitting.

It also supports regex!


$ FOO="something"

$ [[ $FOO =~ ^s(.*)e(.*)n ]]

$ declare -p BASH_REMATCH
declare -a BASH_REMATCH=([0]="somethin" [1]="om" [2]="thi")


It's very powerful and purely additive over [

But it doesn't matter when pointing out how bash does whitespace
splitting of commands. :)


>  [And it's even support
> by busybox's ash shell.]



Beware that busybox ash supports [[ "partially".

From the busybox source code comments:



/* BASH_TEST2: [[ EXPR ]]
 * Status of [[ support:
 *   && and || work as they should
 *   = is glob match operator, not equality operator: STR = GLOB
 *   == same as =
 *   =~ is regex match operator: STR =~ REGEX
 * TODO:
 * singleword+noglob expansion:
 *   v='a b'; [[ $v = 'a b' ]]; echo 0:$?
 *   [[ /bin/n* ]]; echo 0:$?
 * quoting needs to be considered (-f is an operator, "-f" and ""-f are
not; etc)
 * ( ) < > should not have special meaning (IOW: should not require quoting)
 * in word = GLOB, quoting should be significant on char-by-char basis:
a*cd"*"
 */
#define    BASH_TEST2           (ENABLE_ASH_BASH_COMPAT * ENABLE_ASH_TEST)



-- 
Eli Schwartz

Attachment: OpenPGP_signature.asc
Description: OpenPGP digital signature

Reply via email to