if 语句语法错误
if [ (`grep -R -l "${images}" *` | wc -l) == 1 ]
这是行不通的。如果我在命令行执行此操作,那么它会给我一个数字。
grep -R -l "${images}" * | wc -l
我想看看这个数字是否是 1。如果是,就做点什么。如果不做别的事。为什么第一个代码块给我一个语法错误?
我已经更新了我的代码。 image_count 的数字是正确的,但由于某种原因,即使 $image_count 实际上是 1,它总是执行 else 操作。所以我的 if 语句不正确。有人知道为什么吗?
image_count=`grep -R -l "${images}" * | wc -l`
echo $image_count
if [ $image_count == 1 ]; then
new_name=`grep -R -l "slide[0-9]"`
echo new_name
else
echo "non 1"
fi
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
if [ $image_count == 1 ]; then
new_name=`grep -R -l "slide[0-9]"`
echo new_name
else
echo "non 1"
fi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
嗯,测试语句(在
[]
内)似乎是错误的。它有点混合了两种语言:bash 的命令语言(命令、通过管道连接在一起的可执行文件 + 控制流语法)。
OTOH,在上面的
[]
中,它是test
程序的表达语言,请参阅联机帮助页:$ man test : "( 表达式 )" 。表达式不是任意的 shell 命令,而是由基元(字符串、数字等)和运算符(-eq、-oe)构建的东西。
这两种语言之间的桥梁当然是反引号 - 它在其中运行 bash 命令并将输出替换为字符串,然后可以使用该
测试
。因此,正如其他人简要回答的那样,只需将反引号移到左侧的边界即可,即从:
到
UPDATE: 查看您的第二个版本,另一个问题是
==
不是有效的运算符在test
中(再次参见联机帮助页)。使用普通的=
代替。另一方面, bash 本身支持
==
(在最近的版本中) - 有点令人困惑。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 thetest
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:
to
UPDATE: looking at your second version, the other problem is
==
is not a valid operator intest
(again, see manpage). Use plain=
instead.On the other hand,
==
is supported by a bash itself (in recent enough versions) - a bit confusing..使用:
use:
尝试
try
您可以避免复杂的管道使用,并使用 grep 的“-c”选项来输出匹配行的计数。
这里有很多东西,使用“-c”并与数字 1 和字符串 1 进行比较。
(根据 grep 手册,-R 和 -r 是等效的)
You could avoid the complicated pipe usage and use the '-c' option of grep to output the count of matching lines.
Multiple things here, using '-c' and comparing to a number 1, vs a string 1.
(-R and -r are equivalent per the grep manual)