
次のスニペットがあります。
#!/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
答え2
入力を次に変換します。議論:
echo "this is the test" | xargs bash getoptscript.sh -m -
結果は次のとおりです。
bash getoptscript.sh -m - this is the test