各位 UNIX&Linux 用户大家好。我对我在 bash 脚本中编写的一些代码有疑问。我的程序应该执行以下操作:
编写一个脚本,从用户那里读取两个字符串。该脚本将对两个字符串执行三个操作:
(1) 使用 test 命令查看其中一个字符串的长度是否为零,另一个字符串的长度是否非零,并将两个结果告诉用户。 (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”,-z
只需要一个参数。