shell脚本:if语句

时间:2012-06-12 08:55:36

标签: bash shell if-statement

我在这里关注教程:http://bash.cyberciti.biz/guide/If..else..fi#Number_Testing_Script

我的脚本如下:

lines=`wc -l $var/customize/script.php`
if test $lines -le 10
then
    echo "script has less than 10 lines"
else
    echo "script has more than 10 lines"
fi

但我的输出如下:

./boot.sh: line 33: test: too many arguments
script has more than 10 lines

为什么说我的论点太多了?我没有看到我的脚本与教程中的脚本有何不同。

3 个答案:

答案 0 :(得分:10)

wc -l file命令将打印两个单词。试试这个:

lines=`wc -l file | awk '{print $1}'`

要调试bash脚本(boot.sh),您可以:

$ bash -x ./boot.sh

它会打印每一行。

答案 1 :(得分:8)

wc -l file

输出

1234 file

使用

lines=`wc -l < file`

只获取行数。此外,有些人更喜欢这种符号而不是反写:

lines=$(wc -l < file)

此外,由于我们不知道$var是否包含空格,以及文件是否存在:

fn="$var/customize/script.php"
if test ! -f "$fn"
then
    echo file not found: $fn
elif test $(wc -l < "$fn") -le 10
then
    echo less than 11 lines
else
    echo more than 10 lines
fi

答案 2 :(得分:1)

另外,你应该使用

if [[ $lines -gt 10 ]]; then
    something
else
  something
fi

test condition真的已经过时了,它的直接继承者[ condition ]也是如此,主要是因为你必须非常小心这些形式。例如,您必须引用传递给$vartest的任何[ ],还有其他细节会变得毛茸茸。 (测试作为任何其他命令以各种方式处理)。有关详细信息,请查看此article

相关问题