3 ms·
THIS. Why does this: if age < 18 { echo "I'm not an adult yet" } else { echo "I'm an adult" } compile to this: __0_age=30; if
by sgarland 2y ago
THIS. Why does this:
if age < 18 {
echo "I'm not an adult yet"
} else {
echo "I'm an adult"
}
compile to this:
__0_age=30;
if [ $(echo ${__0_age} '<' 18 | bc -l | sed '/\./ s/\. \{0,1\} 0\{1,\}$//') != 0 ]; then
echo "I'm not an adult yet"
else
echo "I'm an adult"
fi
instead of this:
__0_age=30;
if [[ ${__0_age} -lt 18 ]]; then
...
If you're going to compile to Bash, then use Bash-isms.
EDIT: `-gt` is POSIX, but tbf if there's no input sanitization, then bash (or sh) will choke on the float. In that case, as long as you aren't trying to round, you could use parameter substitution to truncate:
__0_age=17.6;
if [[ ${__0_age%%\.*} -lt 18 ]]; then
...
EDIT2: TIL that parameter substitution is POSIX [0] Section 2.6.2
[0]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V...
- nick238 2y agoSo you want it to compile to POSIX sh but you're unhappy it doesn't use more POSIX-incompatible features? Maybe full POSIX sh compat is WIP, or in some simpler cases maybe it already is?
- olejorgenb 2y agoRetr0id, not sgarland want posix. > Maybe full POSIX sh compat is WIP Still - I sure hope it's possible to do a comparison in sh without spawning two processes.
- sgarland 2y agoAs I've just updated my comment to reflect, TIL that parameter substitution is supported (with some exceptions) by `sh`. More broadly though, yes, there's a tendency for people to pop sub-shells without giving it a second thought. Those aren't free; use shell built-ins whenever possible!
- jimrandomh 2y agoThere might be reasons to use `bc` like this if you don't know the type of `age` and it could be a non-numeric string. Buuuuut a programming language where a simple integer-comparison leads to two subprocesses is going to be slower than the slowest existing programming languages, by orders of magnitude.
- chme 2y agoRight. And the check/type validation shouldn't happen on comparison, but on assignment and only if it is dynamically assigned.
- sgarland 2y agoAm I missing something, like `bc` can parse `one + two`? Input sanitizing should be done before trying to hand inputs over to be summed.
- chme 2y agoThe amber source of that is [here](https://docs.amber-lang.com/basic_syntax/basic_syntax https://docs.amber-lang.com/basic_syntax/basic_syntax) and contains: // Define variables let name = "John" let age = 30 // Display a greeting echo "Hello, my name is {name}" // Perform conditional checks if age < 18 { echo "I'm not an adult yet" } else { echo "I'm an adult" } So there is no input, everything is known statically. No sanitation required. Any additional checks done by amber in the bash code is unnecessary.
- joveian 2y ago"if ((age < 18)) ; then ..." works in bash.