linux - bash |管道到 bash 函数

标签 linux bash function pipe stdin

在尝试通过管道传递给 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

但是,在另一个上下文中,我收到了正确的输出以及此错误消息:“段错误(核心已转储)”。

尝试调试它时,我问我在函数内部编写代码以获得 STDIN 的方式是否有问题。

非常感谢。

最佳答案

我不建议将整个标准输入读入一个变量。而不是:

#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

关于linux - bash |管道到 bash 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42719077/

相关文章:

linux - 编辑 Vim 配置

php - 使用 shell 脚本通过 php 运行 mkdir 不工作

c++ - 我可以实现其签名仅基于类型 ID 不同的模板化函数吗?

R-加速与 data.table 子集相关的计算

linux - CentOS 6.3 上 eth0 和 venet0 配置的区别

python - 在 windows 中使用 python 在 linux 上运行远程 perl 脚本

linux - 如何在 ebextensions 脚本中重启 Elastic Beanstalk 实例?

python - 如何在 bash/Python/Fabric/sh 脚本中使用 pew?

Bash 脚本无法在新的专用服务器上运行

mysql - 如何在 MARIADB/MYSQL 中为函数/过程声明表到变量?