次のスクリプトがあります。
echo 'Please select type file , the name of the input file and the name of the output file:
a.plain ( please press a ) <input_file> <output_file>;
b.complex ( please press b ) <input_file> <output_file>;'
read one two three
echo $#
if [ $# -ne 3 ]; then
echo "Insufficient arguments !"
exit 1;
else
echo "Number of passed parameters is ok"
fi
$#
常に0を出力し、後でスクリプトで$ one、$ two、および$ thirdを使用すると、readコマンドは正しい変数を提供します。
ありがとうございます。
ベストアンサー1
すべての変数の値を取得し、それ以外の場合は終了するかどうかをテストするには、-z
空の文字列のテストを使用します。
if [ -z "$one" ] || [ -z "$two" ] || [ -z "$three" ]; then
echo 'Did not get three values' >&2
exit 1
fi
価値$#
は数量です位置パラメータ、通常はコマンドライン引数(またはset
組み込み設定値)です。これらは$1
、$2
など$3
で(または配列として一緒に"$@"
)使用でき、組み込み関数が読み取る値とは無関係ですread
。
スクリプトが入力をインタラクティブに読み取るのではなく、コマンドライン引数として使用するようにします(ユーザーはタブ補完機能を利用でき、使いやすくなり、ユーザーが1つ以上のパスを提供したい場合は好むかもしれません)。端末接続を必要とせずに他のスクリプト内でスクリプトを使用する)
if [ "$#" -ne 3 ]; then
echo 'Did not get three command line arguments' >&2
exit 1
fi
one=$1
two=$2
three=$3
この場合、スクリプトは次のように実行されます。
./script.sh a.plain /path/to/inputfile /path/to/outputfile
入力処理を標準入力で行うことができるかどうか、および出力を標準出力に送信できるかどうか(たとえば、そうでない場合)必要スクリプト内の入出力ファイルへの明示的なパス)、スクリプトは最初の引数(a.plain
またはb.complex
)のみを使用できます。
./script.sh a.plain </path/to/inputfile >/path/to/outputfile
スクリプトは入力と出力に標準入力と標準出力ストリームを使用します。一つコマンドラインパラメータ)。
これにより、他のプログラムからのデータ入力を使用してスクリプトを実行でき、追加の後処理も可能です。
gzip -dc <file-in.gz | ./script.sh a.plain | sort | gzip -c >file-out.gz