如何将用户定义的变量与字符串文字进行比较

时间:2016-11-28 00:41:26

标签: sh

我正在尝试编写一个脚本,允许用户输入文件名并显示文件中的行数,字数,字符数或全部数,具体取决于用户是否输入'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.

有人可以帮我解释这个错误吗?

2 个答案:

答案 0 :(得分:0)

我明白了。 -eq-ne是整数比较运算符。比较字符串时,您必须使用=!=

答案 1 :(得分:0)

此外,您应该在while循环中使用AND conditions

#!/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