On 2024-11-21 20:15, Greg Wooledge wrote:
On Thu, Nov 21, 2024 at 08:14:35 +0100, Erwan David wrote:
On Thu, Nov 21, 2024 at 07:39:33AM CET, Bitfox <h...@bitfox.ddns.net> said:
>
> BTW, what’s the difference between [[ ]] and [ ] here? I know only the
> latter.

IIRC, [[ ]] is a bash/zsh builtin, [ ] is /bin/[ other name of
/bin/test

That's partly correct.  [[ is a "shell keyword" in bash, meaning it can
be parsed differently.  For example, you can put ( ) && || inside it,
which normally wouldn't be allowed.  [ is a "shell builtin" in bash,
which means it has the parsing behavior of an ordinary command.

There are /usr/bin/[ and /usr/bin/test commands as well, but you'll
almost never use those.  The shell builtin commands take precedence,
unless you disable them, or explicitly type out /usr/bin/[ etc.

The behavior of [ and test is dictated by POSIX, which is a set of minimal standards for shell commands (and other things). Shells are free to add their own extensions on top of what POSIX requires, and *all* of them do.

The behavior of [[ is "whatever the shell's developers want it to be",
since it's not a POSIX command at all.

You'll often find that people writing bash script (as opposed to portable
sh scripts) prefer to use [[ because it handles certain things in a
clearer way, as well as providing additional features.  For example,

    [[ $a = 1 ]]            # You don't need quotes around "$a" here.

[[ $file = *.mp3 ]] # The right hand side of = uses glob matching.

    [[ $file =~ $myregex ]] # =~ does a regular expression (ERE) match.

    [[ ( $x -ge 1 ) && ( $y -le 5 ) ]]

The nearest sh equivalents of these would be:

    [ "$a" = 1 ]

    case $file in *.mp3) ...;; esac

    if printf %s "$file" | grep -q -E -- "$myregex"

    [ "$x" -ge 1 ] && [ "$y" -le 5 ]    # Two separate [ commands.

    # DO NOT use [ "$x" -ge 1 -a "$y" -le 5 ].  That's unspecified.

In the specific example code that was posted earliecr in this thread,
the [[ command didn't offer any real advantage over [.  However, since
the script was already a bash script, one presumes the author was simply
following the "use [[ in bash, [ in sh" convention.

Thank you very much. That make things clear.

regards.

Reply via email to