簡體   English   中英

重擊 管道到bash功能

[英]Bash | pipe to bash function

為了嘗試傳遞到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

如果bash負責核心轉儲,那肯定表示應報告bash中的錯誤。 但是,您的函數可以更簡單地編寫為

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

至少可以避免該錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM