Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionals in Posix Standards

Tags:

In these days I spent a lot of time reading various articles and guides about scripting (most of all in Bash). One of the first things that came up was that the best thing to do was sticking to POSIX, for portability.

Anyway, I couldn't get the standard way to make a conditional statement straight... I would like to ignore test in this post and discuss [ and [[ instead.

I found that [ is a bit dated, but every shell supports it (older as alias of /bin/test/, "newer" as part of the shell themselves).

On the other hand, almost every tutorial I found use [[, and, when asked, the reason is something like "Bash is default in most of Linux distributions, so it's like a standard".

There are, of course, a lot of differences between them and personally I found [[ easier to use.

What is the standard way to make a conditional statement? And if a standard way isn't defined: What is the best way? I have to achieve portability, not readability or easiness...

What is the position on "Bash is a de facto standard" and is it really safe to use it as a standard rather than only POSIX rules?

like image 967
ingroxd Avatar asked Apr 23 '18 10:04

ingroxd


1 Answers

Bash-specific

[[ .. ]]

POSIX = sh, like Dash

[ .. ]

As you also asked for personal opinion, mine is: If there is no reason to use the Bash-specific way, always try to adhere to POSIX standards.


Two examples

Comparing strings

in Bash

[[ "$a" == "$b" ]]

in a POSIX shell

[ "$a" = "$b" ]

While loop condition

in Bash

while [[ "$i" > 0 ]]

in a POSIX shell

while [ "$i" -gt 0 ]

Conclusion

While it may seem POSIX is rather harder to use, and it certainly may be at times, it gives you the power to move the script to any shell environment, i.e. portability. For example, you can run the same script on Windows in Cygwin and in any Linux shell.

I realize now, you specifically asked about the if conditional statements, and what I said is perfectly applicable to that question too.

like image 175
LinuxSecurityFreak Avatar answered Sep 28 '22 18:09

LinuxSecurityFreak