Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 860
Roger Avatar asked Sep 25 '26 18:09

Roger


2 Answers

I wouldn't recommending reading the whole stdin into a variable. Instead of:

#the main "worker" function always uses stdin/out
example_worker() { tr ' ' '_'; }

#the switcher
example() { if [[ -z "$1" ]]; then example_worker; else example_worker <<< "$1"; fi ; }

echo 'a b c' | example
example 'a b c'
#but also
example < multi_giga_file.txt
like image 92
jm666 Avatar answered Sep 28 '26 08:09

jm666


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.

like image 42
chepner Avatar answered Sep 28 '26 09:09

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!