DEV Community

Sérgio Araújo
Sérgio Araújo

Posted on

The shell real power

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[@]}
Enter fullscreen mode Exit fullscreen mode

The magic of pipes

seq -s+ 1 2 5 | bc
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
emanoelopes profile image
Emanoel Lopes

Using shell like this is magical. I'll appreciate more examples like this.