bashスクリプトのgetoptsからstdoutをパイプする方法は?

bashスクリプトのgetoptsからstdoutをパイプする方法は?

次のスニペットがあります。

#!/bin/bash

OPTIND=1
while getopts ":m:t" params; do
    case "${params}" in

        m)
             bar=$OPTARG ;;
        t)
            foo=$OPTARG ;;

        \?) 
            "Invalid option: -$OPTARG" >&2
            print_usage 
            exit 2
            ;;

        :)
            echo "Option -$OPTARG requires an argument." >&2
            print_usage
            exit 2
            ;;

        esac

done
shift "$(( OPTIND-1 ))"
echo "${foo}"  && echo  "${bar}"

このスクリプトを使用してstdoutをパイプする方法は?

たとえば、

echo "this is the test" | bash getoptscript.sh -m - 

以下を提供する必要があります。 this is the test出力として。

ベストアンサー1

cat文字列をコマンドライン引数として渡す代わりに、次のようにスクリプトの標準入力を簡単に読み取ることができます。

printf '%s\n' "$foo"
if [ "$bar" = "-" ]; then
    # assume data is on standard input
    cat
else
    print '%s\n' "$bar"
fi

おすすめ記事