こんにちは、UNIXとLinuxユーザーの皆さん。 Bashスクリプトに書いたいくつかのコードについて質問があります。私のプログラムは次のことを行う必要があります。
ユーザーから 2 つの文字列を読み取るスクリプトを作成します。このスクリプトは、2つの文字列に対して3つのことを行います。
(1)テストコマンドを使用して、ある文字列の長さがゼロであること、他の文字列の長さがゼロでないことを確認し、2つの結果をユーザーに通知します。 (2)各文字列の長さを決定し、どちらがより長いか同じ長さかをユーザーに伝えます。 (3) 文字列が等しいか比較します。ユーザーに結果を教えてください。
6 #(1) Use the test command to see if one of the strings is of zero length and if the other is
7 #of non-zero length, telling the user of both results.
8 #(2) Determine the length of each string and tell the user which is longer or if they are of
9 #equal length.
10 #(3) Compare the strings to see if they are the same. Let the user know the result.
11
12 echo -n "Hello user, please enter String 1:"
13 read string1
14 echo -n "Hello User, please enter String 2:"
15 read string2
16
17 myLen1=${#string1} #saves length of string1 into the variable myLen1
18 myLen2=${#string2} #saves length of string2 into the variable myLen2
19
20 if [ -z $string1 ] || [ -z $string2 ]; then
21 echo "one of the strings is of zero length"
22
23 else
24 echo "Length of The first inputted string is: $myLen1"
25 echo "Length of The second inputted string is: $myLen2"
26
27 fi
28
29 if [ $myLen1 -gt $myLen2 ]; then #Determine if string1 is of greater length than string2
30 echo "The First input string has a greater text length than the Second input string."
31 exit 1
32 elif [ $myLen2 -gt $myLen1 ]; then #Determine if String2 is of greater length than String1
33 echo "The second string has a greater text length than the First string."
34 exit 1
35 elif [ $myLen1 -eq $myLen2 ]; then #Determine if the strings have equal length
36 echo "The two strings have the exact same length."
37 exit 1
38 fi
私のスクリプトは次のエラーを受け取ります。 (そうでなければ期待通りに動作します。)
./advnacedlab4.sh: line 20: [: too many arguments
./advnacedlab4.sh: line 20: [: too many arguments
あなたのコメントを教えてください。ありがとうございます!
ベストアンサー1
Jasonwryanが指摘したように、テスト中の文字列の空白から自分自身を保護する必要があります。変数が拡張されたときに単一の単位で処理されるように、変数の周りに引用符を入れるか、代わりにこれらの拡張を処理するためのよりスマートで移植性の高い演算子を使用できます[[
。[
それ以外のスペースがある場合は、次string1
のstring2
式を取得します。
string1="string one"
if [ -z string one ] ...
したがって、2つの文字列「string」と「one」を渡し、1つのパラメータのみを-z
使用します。