2016-11-28 20 views
0

私はスクリプトを記述して、ユーザーがファイル名を入力し、行、単語、文字、または3つすべてのファイルを表示できるようにしようとしています。ユーザーが'l'(行)、'w'(単語)、'c'(文字)、または'a'(すべて)を入力するかどうかを指定します。ここでユーザー定義の変数を文字列リテラルと比較する方法

は、私がこれまで持っているものです。

#!/bin/sh                               

# Prompt for filename                            
read -p 'Enter the file name: ' filename 

# Prompt which of lines, words, or chars to display                    
read -p 'Count lines, words, characters, or all three (l, w, c, a)? ' display 
while [ $display -ne "l" -o $display -ne "w" -o $display -ne "c" -o $display -ne "a" ] 
do 
    echo "Invalid option" 
    read -p 'Count lines, words, characters, or all three (l, w, c, a)? ' display 
done 

# Display to stdout number of lines, words, or chars                    
set `wc $filename` 
if [ $display -eq "l" ] 
then 
    echo "File '$4' contains $1 lines." 
elif [ $display -eq "w" ] 
then 
    echo "File '$4' contains $2 words." 
elif [ $display -eq "c" ] 
then 
    echo "File '$4' contains $3 characters." 
else 
    echo "File '$4' contains $1 lines, $2 words, and $3 characters." 
fi 

私はスクリプトを実行し、ファイルを提供trial.txtと呼ばれ、オプションwを選択した場合、私は出力取得:

./icount: 11: [: Illegal number: w 
./icount: 19: [: Illegal number: w 
./icount: 22: [: Illegal number: w 
./icount: 25: [: Illegal number: w 
File 'trial.txt' contains 3 lines, 19 words, and 154 characters. 

すると誰かが私を助けることができますこのエラーを解釈しますか?

答えて

0

私はそれを理解しました。 -eqおよび-neは整数比較演算子です。文字列を比較するときは、=!=を使用する必要があります。

+0

真でAND conditionsを使用する必要があります。しかし、その訂正をしても、ユーザが空の入力を入力すると、スクリプトが失敗します。入力が 'hi there'、あるいはほとんどの場合' * 'が入力されます。ボーナスポイントについては、引用符を使うか、(通常はksh/bash /などの方が良い) '[[' 'それらを修正する。 –

0

また、あなたは、whileループ

#!/bin/sh                               

# Prompt for filename                            
read -p 'Enter the file name: ' filename 

# Prompt which of lines, words, or chars to display                    
read -p 'Count lines, words, characters, or all three (l, w, c, a)? ' display 
while [ "$display" != "l" -a "$display" != "w" -a "$display" != "c" -a "$display" != "a" ] 
do 
    echo "Invalid option" 
    read -p 'Count lines, words, characters, or all three (l, w, c, a)? ' display 
done 

# Display to stdout number of lines, words, or chars                    

set `wc $filename` 
if [ $display == "l" ] 
then 
    echo "File '$4' contains $1 lines." 
elif [ $display == "w" ] 
then 
    echo "File '$4' contains $2 words." 
elif [ $display == "c" ] 
then 
    echo "File '$4' contains $3 characters." 
else 
    echo "File '$4' contains $1 lines, $2 words, and $3 characters." 
fi 
関連する問題