且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查是否一个文件包含使用bash的特定字符串

更新时间:2022-11-11 12:35:46

 如果grep的-q SomeString$文件;然后
   一些行动
 科幻

您不需要 [[]] 在这里。只需直接运行该命令。添加 -q 选项,当你不需要在字符串显示时,被发现了。

在出口code中的的grep 命令返回0或1,具体取决于
搜索的结果。 0,如果事情被发现;否则为1。

  $回声你好| grep的喜;回声$?
1
$回声你好| grep的他;回声$?
你好
0
$回声你好| grep的-q他;回声$?
0

您可以像的的条件中指定的命令。如果其退出code中的命令返回0,这意味着该条件是真实的;否则为false。

  $如果/斌/真;然后回显这是真的;科幻
那是真实的
如果$ /斌/假;然后回显这是真的;科幻
$

正如你可以看到你在这里直接运行程序。无需额外的 [] [[]]

I want to check if a file contains a specific string or not in bash. I used this script, but it doesn't work:

 if [[ 'grep 'SomeString' $File' ]];then
   Some Actions
 fi

what's wrong in my code?

 if grep -q SomeString "$File"; then
   Some Actions
 fi

You don't need [[ ]] here. Just run the command directly. Add -q option when you don't need the string displayed when it was found.

The grep command returns 0 or 1 in the exit code depending on the result of search. 0 if something was found; 1 otherwise.

$ echo hello | grep hi ; echo $?
1
$ echo hello | grep he ; echo $?
hello
0
$ echo hello | grep -q he ; echo $?
0

You can specify commands as an condition of if. If the command returns 0 in its exitcode that means that the condition is true; otherwise false.

$ if /bin/true; then echo that is true; fi
that is true
$ if /bin/false; then echo that is true; fi
$

As you can see you run here the programs directly. No additional [] or [[]].