简体   繁体   English

重击 管道到bash功能

[英]Bash | pipe to bash function

In the attempt to pipe to a Bash function, I wrote this: 为了尝试传递到Bash函数,我这样写:

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. 尝试调试它时,我问我在函数内部编写代码的方式是否有问题以获得STDIN。

Thanks a lot. 非常感谢。

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

If bash is responsible for the core dump, that certainly indicates a bug in bash that should be reported. 如果bash负责核心转储,那肯定表示应报告bash中的错误。 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. 至少可以避免该错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM