shell - var if length,if条件给出错误

时间:2013-12-30 07:40:57

标签: bash shell if-statement grep

我试图看看我是否用这个

找到了使用grep的东西
found=`grep -F "something" somefile.txt`

if ((${#found} == 0)); then
   echo "Not Found"
else
   echo "Found"
fi

我成功使用了上述逻辑,如果grep找到了某些内容,它会将输出存储在found变量中,但我面临的问题是if条件。每当found=0它给我一些错误时

  

final.sh:13:final.sh:0:未找到

仅供参考:final.sh是脚本名称

4 个答案:

答案 0 :(得分:3)

问题是你正在编写bash特定代码,但是用sh运行它。在bash中,(( .. ))是算术上下文,而在POSIX sh中,它只是两个嵌套的子shell,导致它尝试将该数字作为命令执行。

如果您以这种方式调用,则可以通过在shebang中指定#!/bin/bash和/或使用bash yourfile而不是sh yourfile来使用bash而不是sh来运行它。

但是,您的示例的正确方法是直接使用grep的退出状态:

if grep -q something somefile
then
  echo "found"
else
  echo "not found"
fi

答案 1 :(得分:1)

要检查文件中是否有某个字符串,可以使用grep

中的返回状态
grep -q something somefile.txt
if [ $? -eq 0 ]
then
  echo "found"
else
  echo "not found"
fi

更短的表格

grep -q something somefile.txt && echo found || echo not found

答案 2 :(得分:1)

found=$(grep -F "something" somefile.txt)
if [ $? = 0 ]; then # $? is the return status of a previous command. Grep will return 0 if it found something, and 1 if nothing was found.
    echo "Something was found. Found=$found"
else
    echo 'Nothing was found'
fi

我觉得这段代码比其他答案更优雅 但无论如何,你为什么要写sh?你为什么不用bash?您确定需要这种便携性吗? Check out this link以确定您是否真的需要sh

答案 3 :(得分:0)

以下是我如何做这件事:

found=$(grep -F "something" somefile.txt)

if [[ -z $found ]]; then
    echo "Not found"
else
    echo "Found"
fi