3 ms·
Yeah, honestly POSIX shell already has C arithmetic, so it would be natural for it to have set operations, a la Python (x | y, x & y, etc.) Here's Fizz Buzz i
by chubot 10y ago
Yeah, honestly POSIX shell already has C arithmetic, so it would be natural for it to have set operations, a la Python (x | y, x & y, etc.) Here's Fizz Buzz in shell, without executing external processes like "expr":
for x in $(seq 100); do
{ (( x % 5 == 0 )) && (( x % 3 == 0 )) && echo "$x fizzbuzz"; } ||
{ (( x % 5 == 0 )) && echo "$x buzz"; } ||
{ (( x % 3 == 0 )) && echo "$x fizz"; } ||
echo "$x"
done
I'm a big fan of the Unix philosophy, but after a few decades, it makes sense to fold commonly-used operations into the shell, especially when they cost almost nothing to implement with zero bugs. There's no benefit to "streaming" for these operations; on the contrary, it's probably an de-optimization.
I plan to add set expressions to my new shell: http://www.oilshell.org/blog/ http://www.oilshell.org/blog/
credit: https://github.com/Aricg/FizzBuzz---Bash/blob/master/FizzBuzz.bash https://github.com/Aricg/FizzBuzz---Bash/blob/master/FizzBuz...
- arthur2e5 10y agoA few gotchas here: * "seq" is usually an external process. You may want to do it in bash's arithmetic for, use a while loop with `$(( ... ))", or write a `seq` function (you still need to spawn a subshell for command expansion though.) * "(( ... ))" is not in POSIX shell, but "$(( ... ))" is. You should be able to get around with some [ "$(( blah ))" -eq 0 ] tests.
- chubot 10y agoYes you're right that (( )) isn't POSIX but $(( )) is -- I was lazy and borrowed it from the example. The one change I made was to change brace expansion {1..100} to $(seq 100) because the former isn't in POSIX, but yeah the whole thing wasn't POSIX anyway. But it doesn't really detract from the point -- if shell has arithmetic and bitwise operators built in, it's not a stretch for it to have set operations built in.