Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: How to build a recursive cowsay

Tags:

linux

bash

Here's a linux command (you might need the cowsay application.

cowsay 'moo'

Here's another command:

cowsay 'moo' | cowsay -n

The result is pretty entertaining:

 ______________________________
/  _____                       \
| < moo >                      |
|  -----                       |
|         \   ^__^             |
|          \  (oo)\_______     |
|             (__)\       )\/\ |
|                 ||----w |    |
\                 ||     ||    /
 ------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

Now, of course, it's pretty fun to repeat that piped command N times. It looks a little like this:

 cowsay 'moo' | cowsay -n | cowsay -n | cowsay -n | cowsay -n | cowsay -n | cowsay -n | cowsay -n | cowsay -n | cowsay -n | cowsay -n | cowsay -n

Cows nested inside cows saying things

But I'm thinking there must be a neater way of achieving this. Let's just say I want 500 cows all saying each other, or 1,000, or 1,000,000. Surely I don't just have to keep my finger on the paste button?

Here's the question; is there a way in bash (command or script) to recursively pass the output of a command into itself a given number of times?

like image 449
AJFaraday Avatar asked Apr 07 '17 07:04

AJFaraday


1 Answers

cowsayN() {
    local n=$1
    shift
    if ((n>1)); then
        cowsay -n | cowsayN $((n-1))
    else
        cowsay -n
    fi
}
echo 'moo' | cowsayN 500
like image 121
ephemient Avatar answered Sep 23 '22 13:09

ephemient