Skip to content
Advertisement

Bash | pipe to bash function

In the attempt to pipe to a Bash function, I wrote this:

example () {
    if [ -z ${1+x} ]; then local S=${@:-$(</dev/stdin)}; else local S="$1"; fi
    #echo "$S"
    echo "$S" | tr ' ' '_'
}
echo 'Moizès Júnior' | example
example 'Moizès Júnior'

Moizès_Júnior
Moizès_Júnior

However, in another context I am receiving the correct output plus this error message: “Segmentation fault (core dumped)”.

Trying to debug it I ask if there is something wrong the way I am writing the code inside the function in order to get STDIN.

Thanks a lot.

Advertisement

Answer

If bash is responsible for the core dump, that certainly indicates a bug in bash that should be reported. However, your function can be written more simply as

example () {
    local S
    if (( "$#" == 0 )); then
        IFS= read -r S
        set -- "$S"
    fi
    echo "${1// /_}"
}

which may, at least, avoid the bug.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement