开发者

if statement syntax error

if [ (`grep -R -l "${images}" *` | wc -l) == 1 ]

This is not working. If I do this at the command line then it will give me a number.

grep -R -l "${images}" * | wc -l

I want to see if that number is a 1. If it is do something. If not do something else. Why is the first code chunk giving me a sytax error?

I have updated my code. image_count is correct with the number but for some reason it is always doing the else even if $image_count is really 1. So my if statement isn't right. Anyone know why?

image_count=`grep -R -l "${images}" * | wc -l`
echo $image_count开发者_StackOverflow
if [ $image_count == 1 ]; then
new_name=`grep -R -l "slide[0-9]"`
echo new_name
else
echo "non 1"
fi


So my if statement isn't right. Anyone know why?

Well it's the test statement (within [ ]) that seems wrong. It's kind of mixing up two languages: bash's command language (which are commands,executables piped together + control flow syntax).

OTOH, within the [] above, it's an expression language of the test program, see the manpage: $ man test : "( EXPRESSION )" .

Expression there is not an arbitrary shell command, but something built up from primitives (strings, numbers,etc) and operators (-eq, -oe).

One bridge between these two languages is of course the backtick- which runs the bash command therein and substitutes the output as a string, which test then can work with.

So, as others replied briefly, just move out the backticks to the boundary of the left side, ie from:

if [ (`grep -R -l "${images}" *` | wc -l) == 1 ]

to

if [ `grep -R -l "${images}" * | wc -l` = 1 ]

UPDATE: looking at your second version, the other problem is == is not a valid operator in test (again, see manpage). Use plain = instead.

On the other hand, == is supported by a bash itself (in recent enough versions) - a bit confusing..


use:

if [ `grep -R -l "${images}" * | wc -l` == 1 ]


foo=`grep -R -l "${images"} * | wc -l`
if [ $? -ne 0 ]; then
    if [ $foo == 1 ]; then
        echo "1 file found";
    else
        echo "$foo files found";
    fi
else 
    echo "no files found";
fi


try

#!/bin/bash
if [ `grep -R -l "${images}" * | wc -l` == "1" ]; then
  echo "hazzar!"
fi


You could avoid the complicated pipe usage and use the '-c' option of grep to output the count of matching lines.

if [ $( grep -rlc "${images}" * ) -eq 1 ]; then

Multiple things here, using '-c' and comparing to a number 1, vs a string 1. (-R and -r are equivalent per the grep manual)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜