DEV Community
How some people use shell (to sum odd numbers for example)
sum_odd_int_array() {
local sum=0
for x in "$@"; do
if (( x % 2 != 0 )); then
(( sum+=x ))
fi
done
echo $sum
}
array=(1 2 3 4 5)
sum_odd_int_array ${array[@]}
The magic of pipes
seq -s+ 1 2 5 | bc
I can generate a list of odd numbers any size I want using the command seq. And it can even give me a separator different from a new line...
...Then I get the output of the seq command directlly to the next command using a pipe |
. The magic creation of the same guys who created the C language. The bc command finishes the job nicelly.
I could have used command substitution to make things seem more complicated but the kiss principle does not allows me do that.
The lesson
Not always, but most of the time you do not need to write complicated shell scripts when you know most of gnu programs. There are many one-linners articles out there to prove my point. I will put some of them here later.
For further actions, you may consider blocking this person and/or reporting abuse
Read next
Automate Foreign Key Index Checks in PostgreSQL: A Practical Bash Script
Dmitry Romanoff -
🚀 Automating React Project Setup with Vite, TypeScript, and Panda CSS Using a Shell Script 🐼
Bharat -
Optimizing PostgreSQL Buffer Cache: Automating Analysis with a Bash Script
Dmitry Romanoff -
15 Linux commands I’ve used most recently and love in general
Kristian Ivanov -
Top comments (1)
Using shell like this is magical. I'll appreciate more examples like this.