Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a following bash script I encountered on the web that prints the power set of a given lines of elements.

p() { [ $# -eq 0 ] && echo || (shift; p "$@") |
        while read r ; do echo -e "$1 $r\n$r"; done }

after the first && there is echo that does not have any argument.

Here is the code to test it:

p $(echo -e "1\n2\n3")
share|improve this question
    
Have you tried it on the CLI? A zero-argument echo just produces a blank line. I'm guessing this is for formatting purposes. –  Joseph R. Apr 1 '13 at 9:33
    
It is not for formatting purposes. Nothing gets printed out without it. –  Forethinker Apr 1 '13 at 9:56

1 Answer 1

up vote 2 down vote accepted

It is for formatting purposes.

$ p() { [ $# -eq 0 ] && echo || (shift; p "$@") |
>         while read r ; do echo -e "$1 $r\n$r"; done }
$ p $(echo -e "1\n2\n3")
1 2 3
2 3
1 3
3
1 2
2
1

$ p                 

$

Note the blank line between the single p and the next prompt. This is echo.

Here it is with more readability:

p() {
    if [ $# -eq 0 ]; then
        echo
    else
        (shift; p "$@") | while read r;
            do echo -e "$1 $r\n$r";
        done
    fi
}

The reason you state it didn't work without it is because it does matter that some command is there, as otherwise the logic is broken (although, as it is, the logic is kind of strange).

share|improve this answer
    
thanks for the more readable code. It makes sense to have the base case to stop the recursion. –  Forethinker Apr 1 '13 at 11:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.