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.
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.